Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Merging Multiple Dictionaries in Python

1 min read .
Merging Multiple Dictionaries in Python

Combining dictionaries is common when assembling configuration, request data, defaults, or results from multiple sources. Python provides several approaches, and the right one depends on the Python version and whether you want to mutate an existing dictionary.

1. Dictionary Union with | (Python 3.9+)

Modern Python supports the dictionary union operator:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict3 = {"d": 5}

merged = dict1 | dict2 | dict3
print(merged)

Output:

{'a': 1, 'b': 3, 'c': 4, 'd': 5}

When duplicate keys exist, the value from the dictionary on the right wins.

The original dictionaries are unchanged.

2. Dictionary Unpacking with ** (Python 3.5+)

merged = {**dict1, **dict2, **dict3}

This has the same last-value-wins behavior and creates a new dictionary.

Dictionary unpacking remains useful when you need to combine mappings inside a dictionary literal:

config = {
    "debug": False,
    **environment_config,
    **user_config,
}

3. Mutate a Copy with update()

For code that must work on older Python versions or when you want explicit mutation:

merged = dict1.copy()
merged.update(dict2)
merged.update(dict3)

This preserves dict1 while modifying the copy.

To modify an existing dictionary directly:

dict1.update(dict2)

4. In-Place Union with |= (Python 3.9+)

merged = dict1.copy()
merged |= dict2
merged |= dict3

Unlike plain |, |= mutates the left-hand dictionary.

5. Duplicate Keys Are Not Combined Automatically

Suppose both mappings contain a list:

left = {"tags": ["python"]}
right = {"tags": ["linux"]}

A normal merge gives:

print(left | right)
# {'tags': ['linux']}

If your application should combine values instead, that is separate business logic:

merged = {"tags": left["tags"] + right["tags"]}

Conclusion

For Python 3.9 and newer, dict1 | dict2 is usually the clearest way to create a merged dictionary. Use {**a, **b} when dictionary unpacking fits a literal naturally, and update() or |= when mutation is intentional. In every standard merge, later values replace earlier values for duplicate keys.

Related Posts

chevron-up