Append a dictionary to a dictionary
How can you append one dictionary to another in Python? Learn how to merge or update dictionaries using simple methods like the update() function or the ** unpacking operator for clean and efficient code.
Appending one dictionary to another in Python is commonly done when you want to combine or update key-value pairs. While Python dictionaries don’t have a direct “append” method like lists, you can merge them using a few simple approaches.
Method 1: Using update()
This is the most straightforward way:
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
- update() adds all key-value pairs from dict2 to dict1.
- If any keys are the same, the values in dict1 will be overwritten.
Method 2: Using ** Unpacking (Python 3.5+)
A more modern and clean approach:
combined = {**dict1, **dict2}
print(combined) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
- This creates a new dictionary without modifying the originals.
- Also handles key overwriting if duplicates exist.
Method 3: Using a Loop (if more control is needed)
for key, value in dict2.items():
dict1[key] = value
Useful if you want to apply some condition before adding values.
Tips:
- Be careful with overlapping keys—values will be overwritten.
- Use update() when you’re okay modifying the original dictionary.
- Use unpacking (**) if you prefer to keep the originals intact.
Combining dictionaries in Python is super easy—and knowing multiple ways helps you choose what fits best for your code!