In Python, dictionaries are mutable collections of key–value pairs. You can easily add new items to a dictionary using:
update() to add multiple items or merge dictionaries.key: value pairs.update() can add multiple key–value pairs at once.update() will overwrite its value.1) Add a single item by assignment
dictionary[new_key] = value
2) Add multiple items using update()
dictionary.update({key1: value1, key2: value2})
You can add a new key–value pair to a dictionary by assigning a value to a key that does not exist yet.
person = {"name": "Alice", "age": 25}
person["city"] = "New York"
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'New York'}
The update() method allows you to add multiple key–value pairs at once from another dictionary or iterable of pairs.
person = {"name": "Alice", "age": 25, "city": "New York"}
person.update({
"email": "alice@example.com",
"phone": "123-456-7890"
})
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'New York', 'email': 'alice@example.com', 'phone': '123-456-7890'}
When the same key appears in both dictionaries, the value from the dictionary passed to update() wins.
defaults = {"theme": "light", "font": "Arial", "size": 12}
user_settings = {"theme": "dark", "size": 14}
defaults.update(user_settings)
print(defaults)
# {'theme': 'dark', 'font': 'Arial', 'size': 14}
For the single-item example:
Start: {"name": "Alice", "age": 25}
After person["city"] = "New York", the key "city" is added.
Printed dictionary:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
For the update() example:
The call to person.update({...}) adds both "email" and "phone" in one step. If any of those keys already existed, their values would be replaced with the new ones.
For the merging example:
"theme" changes from "light" to "dark"."size" changes from 12 to 14."font" remains "Arial" because it is not present in user_settings.update() when adding multiple items or merging two dictionaries.update() on it will overwrite its value.student with keys like "name" and "roll_no". Add a new key "grade" using assignment.update() to add "email" and "phone" to the same student dictionary.defaults and custom, then merge them with defaults.update(custom) and observe which values are kept.update() with a list of tuples, e.g. person.update([("country", "USA")]).