How to Merge Dictionaries Using ** Operator in Python
You can merge dictionaries in Python by using the
** operator inside a new dictionary literal, like {**dict1, **dict2}. This creates a new dictionary containing all keys and values from both dictionaries, with later keys overwriting earlier ones if duplicates exist.Syntax
The syntax to merge dictionaries using the ** operator is:
{**dict1, **dict2, ...}: Creates a new dictionary by unpacking all key-value pairs from each dictionary.- Each
**dictunpacks the dictionary's items into the new dictionary. - If keys repeat, the value from the last dictionary with that key is used.
python
merged_dict = {**dict1, **dict2}Example
This example shows how to merge two dictionaries using the ** operator. The second dictionary's values overwrite duplicates from the first.
python
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)Output
{'a': 1, 'b': 3, 'c': 4}
Common Pitfalls
Common mistakes when using the ** operator to merge dictionaries include:
- Trying to merge non-dictionary types, which causes a
TypeError. - Expecting the original dictionaries to change; the
**operator creates a new dictionary and does not modify the originals. - Not realizing that keys in later dictionaries overwrite earlier ones silently.
python
wrong = {**['a', 'b']} # Raises TypeError because list is not a dict
# Correct way:
d1 = {'x': 1}
d2 = {'y': 2}
merged = {**d1, **d2} # Works fineQuick Reference
Summary tips for merging dictionaries with ** operator:
- Use
{**dict1, **dict2}to merge into a new dictionary. - Later dictionaries overwrite earlier keys if duplicated.
- Works in Python 3.5 and later.
- Original dictionaries remain unchanged.
Key Takeaways
Use {**dict1, **dict2} to merge dictionaries into a new one in Python.
If keys repeat, the value from the last dictionary is kept.
The original dictionaries are not changed by this operation.
Only dictionaries can be unpacked with **; other types cause errors.
This method requires Python 3.5 or newer.