How do I add a new key to an existing dictionary? It doesn't have an .add() method.

 

To add a new key-value pair to an existing dictionary in Python, you can simply assign a value to the new key using the assignment operator (=). If the key already exists, its value will be updated; if the key doesn't exist, it will be added along with the corresponding value.

Here's an example:

python
# Existing dictionary my_dict = { "name": "Alice", "age": 30, "city": "New York" } # Add a new key-value pair my_dict["occupation"] = "Engineer" # Print the updated dictionary print(my_dict)

In this example, the new key "occupation" is added with the value "Engineer". If you print the my_dict dictionary after adding the new key, you'll see the updated dictionary:

arduino
{'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}

If the key "occupation" already existed, its value would have been updated. Since it didn't exist, a new key-value pair was added.

You can use this approach to add new keys to dictionaries in Python.

Comments