Dictionaries in Python are mutable, allowing you to add new key-value pairs or update existing ones dynamically. There are multiple ways to add to a dictionary, each suited to different scenarios.
You can add a new key-value pair to a dictionary by directly assigning a value to a new key.
1. Add a New Key-Value Pair:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Explanation:
'city' to my_dict and assign it the value 'New York'.
If the key already exists in the dictionary, assigning a value to that key will update the existing entry.
2. Update an Existing Key:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
print(my_dict)
Output:
{'name': 'Alice', 'age': 26}
Explanation:
'age' already exists, so its value is updated from 25 to 26.
update() Method
The update() method allows you to add multiple key-value pairs to a dictionary at once or update existing keys.
3. Add Multiple Key-Value Pairs Using update():
my_dict = {'name': 'Alice', 'age': 25}
my_dict.update({'city': 'New York', 'email': 'alice@example.com'})
print(my_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com'}
Explanation:
update() method adds the new keys 'city' and 'email' to my_dict.
4. Update Existing Keys Using update():
my_dict = {'name': 'Alice', 'age': 25, 'city': 'Boston'}
my_dict.update({'age': 26, 'city': 'New York'})
print(my_dict)
Output:
{'name': 'Alice', 'age': 26, 'city': 'New York'}
Explanation:
update() method updates the existing keys 'age' and 'city' with new values.
Dictionaries can contain other dictionaries, and you can add a new nested dictionary by assigning a dictionary to a new key.
5. Add a Nested Dictionary:
my_dict = {'name': 'Alice', 'age': 25}
my_dict['address'] = {'street': '123 Main St', 'city': 'New York'}
print(my_dict)
Output:
{'name': 'Alice', 'age': 25, 'address': {'street': '123 Main St', 'city': 'New York'}}
Explanation:
'address' is added with a nested dictionary as its value.
In Python 3.9 and later, you can merge two dictionaries using the | (pipe) operator.
6. Merge Two Dictionaries:
dict1 = {'name': 'Alice', 'age': 25}
dict2 = {'city': 'New York', 'email': 'alice@example.com'}
merged_dict = dict1 | dict2
print(merged_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com'}
Explanation:
| operator merges dict1 and dict2 into a new dictionary merged_dict.
update() method when you need to add multiple key-value pairs or update existing ones in a single operation.
Adding to a dictionary in Python is a versatile and essential skill, whether you're working with simple key-value pairs or complex nested structures. By mastering these techniques, you can efficiently manage and manipulate dictionaries in your Python programs.
Jorge García
Fullstack developer