0
0
PythonHow-ToBeginner · 3 min read

How to Update Dictionary in Python: Syntax and Examples

You can update a dictionary in Python using the update() method, which adds key-value pairs from another dictionary or iterable. Alternatively, assign a value to a key directly with dict[key] = value to add or change entries.
📐

Syntax

The main way to update a dictionary is using the update() method. It takes another dictionary or an iterable of key-value pairs and adds or replaces entries in the original dictionary.

  • dict.update(other_dict): Adds all key-value pairs from other_dict.
  • dict[key] = value: Sets or updates the value for a single key.
python
my_dict.update(other_dict)
my_dict[key] = value
💻

Example

This example shows how to update a dictionary with another dictionary and how to add or change a single key-value pair.

python
my_dict = {'apple': 1, 'banana': 2}
other_dict = {'banana': 3, 'cherry': 4}

# Update with another dictionary
my_dict.update(other_dict)
print(my_dict)  # {'apple': 1, 'banana': 3, 'cherry': 4}

# Update a single key
my_dict['apple'] = 5
print(my_dict)  # {'apple': 5, 'banana': 3, 'cherry': 4}
Output
{'apple': 1, 'banana': 3, 'cherry': 4} {'apple': 5, 'banana': 3, 'cherry': 4}
⚠️

Common Pitfalls

One common mistake is trying to update a dictionary with a list of keys instead of key-value pairs, which causes an error. Also, using update() replaces existing keys but does not merge nested dictionaries.

Wrong way:

my_dict.update(['a', 'b'])  # Error: must be key-value pairs

Right way:

my_dict.update({'a': 1, 'b': 2})
python
my_dict = {'a': 1}

# Wrong: causes TypeError
# my_dict.update(['a', 'b'])

# Right:
my_dict.update({'b': 2, 'c': 3})
print(my_dict)  # {'a': 1, 'b': 2, 'c': 3}
Output
{'a': 1, 'b': 2, 'c': 3}
📊

Quick Reference

Summary of ways to update a dictionary:

MethodDescriptionExample
update()Add or replace multiple key-value pairsdict.update({'key': value})
AssignmentAdd or replace a single key-value pairdict[key] = value
setdefault()Add key with default if not presentdict.setdefault(key, default)

Key Takeaways

Use update() to add or replace multiple entries in a dictionary.
Assign a value to a key directly to add or update a single entry.
update() requires key-value pairs, not just keys.
Updating replaces existing keys but does not merge nested dictionaries.
Use setdefault() to add a key only if it is missing.