How to Add New Keys to a Python Dictionary?
To add a new key-value pair to an existing Python dictionary, follow these steps:
- Access the dictionary to which you want to add a new key-value pair.
- Use the square bracket notation to specify the new key value that you want to add.
- 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.