Python dictionaries are mutable, which means you can change their contents after creation. You can:
update() method to change multiple items or merge dictionaries at once.Understanding how to change dictionary items is essential for working with dynamic data like user profiles, settings, and configuration objects.
update() method: Change multiple keys or add new ones using another dictionary or key-value pairs.? Update an existing key
dict_name[key] = new_value changes the value mapped to key.
➕ Add a new key-value pair
If key does not exist, dict_name[key] = value creates it.
? Using update()
dict_name.update(other_dict) will:
From Python 3.7+, dictionaries preserve insertion order, which makes updates predictable in terms of order when you print or iterate over them.
Change the value of an existing key by assigning a new value to that key.
person = {"name": "Alice", "age": 25, "city": "New York"}
person["age"] = 26
print(person)
# {'name': 'Alice', 'age': 26, 'city': 'New York'}
If the key does not exist, assigning a value to it will add a new key-value pair.
person["email"] = "alice@example.com"
print(person)
# {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
The update() method can modify multiple keys at once or add new key-value pairs from another dictionary.
person.update({"age": 27, "city": "Los Angeles", "phone": "123-456-7890"})
print(person)
# {'name': 'Alice', 'age': 27, 'city': 'Los Angeles', 'email': 'alice@example.com', 'phone': '123-456-7890'}
{"name": "Alice", "age": 25, "city": "New York"}age to 26:{'name': 'Alice', 'age': 26, 'city': 'New York'}email:{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}update():{'name': 'Alice', 'age': 27, 'city': 'Los Angeles', 'email': 'alice@example.com', 'phone': '123-456-7890'}Notice how the same person dictionary keeps getting modified. No new dictionary is created — you are changing the original object in memory.
update() when you need to modify or add multiple items at once.update() is a clean way to apply overrides."genre" to your book dictionary.update() to:
"rating" or "pages".update().