How to Add New Keys to a Python Dictionary?

python

To add a new key-value pair to an existing Python dictionary, follow these steps:

  1. Access the dictionary to which you want to add a new key-value pair.
  2. Use the square bracket notation to specify the new key value that you want to add.
  3. Assign a value to the new key using the equal sign.

Here's an example code snippet demonstrating adding a new key to a Python dictionary:

# define the dictionary
my_dict = {"name": "John", "age": 30, "gender": "Male"}

# add a new key-value pair
my_dict["city"] = "New York"

# print the updated dictionary
print(my_dict)

This code will output the following dictionary:

{'name': 'John', 'age': 30, 'gender': 'Male', 'city': 'New York'}

As you can see, the new key-value pair ("city": "New York") has been successfully added to the dictionary.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?