How to Add Key Value Pair to Dictionary in Python
To add a key value pair to a dictionary in Python, use the syntax
dictionary[key] = value. This assigns the value to the specified key, adding it if the key does not exist or updating it if it does.Syntax
The syntax to add or update a key value pair in a Python dictionary is simple:
dictionary: Your existing dictionary variable.key: The key you want to add or update.value: The value to assign to the key.
Using dictionary[key] = value will add the pair if the key is new or update the value if the key already exists.
python
dictionary[key] = value
Example
This example shows how to add a new key value pair to a dictionary and how updating an existing key works.
python
my_dict = {'apple': 2, 'banana': 3}
# Add a new key value pair
my_dict['orange'] = 5
# Update an existing key
my_dict['banana'] = 4
print(my_dict)Output
{'apple': 2, 'banana': 4, 'orange': 5}
Common Pitfalls
One common mistake is trying to use a method like add() which does not exist for dictionaries. Another is forgetting that keys must be immutable types like strings or numbers.
Also, using dictionary.get(key) does not add a key; it only retrieves a value or returns None if the key is missing.
python
my_dict = {'a': 1}
# Wrong: no add() method for dict
# my_dict.add('b', 2) # This will cause an error
# Correct way
my_dict['b'] = 2
print(my_dict)Output
{'a': 1, 'b': 2}
Quick Reference
Here is a quick summary of how to add or update key value pairs in a dictionary:
| Action | Syntax | Description |
|---|---|---|
| Add or update key | dictionary[key] = value | Adds new key or updates existing key with value |
| Check if key exists | if key in dictionary: | Checks if key is present |
| Retrieve value safely | dictionary.get(key, default) | Gets value or default if key missing |
Key Takeaways
Use dictionary[key] = value to add or update key value pairs in Python dictionaries.
Keys must be immutable types like strings, numbers, or tuples.
There is no add() method for dictionaries; assignment is the way to add keys.
Using dictionary.get(key) only retrieves values and does not add keys.
Updating a key that exists will overwrite its previous value.