Merge Dictionnaries

Merging dictionaries is a common task in Python when you want to combine the key-value pairs from two (or more) dictionaries into a single one. Python offers several ways to do this, depending on your version and your needs.

Using the | Operator (Python 3.9+)

Starting with Python 3.9, you can use the | (pipe) operator to merge two dictionaries. This creates a new dictionary containing the keys and values from both.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2
print(merged)  # Output: {'a': 1, 'b': 3, 'c': 4}
  • If the same key exists in both, the value from the second dictionary (dict2) is used.

Using the update() Method

The update() method adds the key-value pairs from one dictionary into another. This modifies the original dictionary in place.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}
  • Note: dict1 is changed. If you want to keep the originals, copy first:
merged = dict1.copy()
merged.update(dict2)

Using Dictionary Unpacking (**)

You can use the unpacking operator ** to merge dictionaries into a new one. This works in Python 3.5+.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)  # Output: {'a': 1, 'b': 3, 'c': 4}
  • Later values overwrite earlier ones for duplicate keys.

Merging More Than Two Dictionaries

All these methods can be extended to merge more than two dictionaries:

d1 = {'a': 1}
d2 = {'b': 2}
d3 = {'c': 3}
merged = {**d1, **d2, **d3}
print(merged)  # Output: {'a': 1, 'b': 2, 'c': 3}

Summary

  • Use | (Python 3.9+) for a clean, new merged dictionary.
  • Use update() to add items to an existing dictionary (in-place).
  • Use {**d1, **d2} for a new dictionary (Python 3.5+).
  • For duplicate keys, later values overwrite earlier ones.

Continue Learning

Python Variables

Popular

Getting Started: Understanding Variables in Python In programming, we often need to store informatio

Python Dictionnaries

For You

Storing Data as Key-Value Pairs: Understanding Dictionaries in Python We've learned about Lists and

Python Strings

For You

Working with Text: Understanding Strings in Python Text is everywhere in the world of programming. W

Personalized Recommendations

Log in to get more relevant recommendations based on your reading history.