Add Dictionary Items
Adding New Key-Value Pairs
A new item can be added to a dictionary by assigning a value to a key that does not already exist. If the key exists, its value will be updated.
Example
# Adding items to a dictionary
person = {"name": "John", "age": 30}
# Add single item
person["city"] = "New York"
print(person)
# Add multiple items with update()
person.update({"country": "USA", "occupation": "Engineer"})
print(person)
Output
{'name': 'John', 'age': 30, 'city': 'New York'} {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA', 'occupation': 'Engineer'}
Merging Dictionaries
Two dictionaries can be combined using update() or with the merge (|) operator in Python 3.9+. update() modifies the original dictionary in place, while the | operator creates a new merged dictionary.
Example
# Merging dictionaries
person = {"name": "John", "age": 30}
address = {"city": "New York", "country": "USA"}
# Using update()
person.update(address)
print("After update:", person)
# Using | operator (Python 3.9+)
person = {"name": "John", "age": 30}
merged = person | address
print("Merged:", merged)
Output
After update: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'} Merged: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Dictionary Comprehensions
Dictionary comprehensions allow creating dictionaries in a single expression. They can also be used to build additional items and merge them into an existing dictionary.
Example
# Creating a dictionary with comprehension
squares = {x: x**2 for x in range(1, 6)}
print("Squares:", squares)
# Adding to existing dictionary with comprehension
person = {"name": "John", "age": 30}
additional_info = {f"info_{i}": f"value_{i}" for i in range(3)}
person.update(additional_info)
print("Updated person:", person)
Output
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Updated person: {'name': 'John', 'age': 30, 'info_0': 'value_0', 'info_1': 'value_1', 'info_2': 'value_2'}