Skip to content
Python

Dictionary Merging

Multiple ways to merge dictionaries.

By EZ4Code Team
dictmerge

Code

# Python 3.9+ uses | operator
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = d1 | d2
print(merged)  # {'a': 1, 'b': 3, 'c': 4}

# Using ** unpacking
merged2 = {**d1, **d2}

# Using update
d1.update(d2)

# Deep merge
def deep_merge(a, b):
    for k, v in b.items():
        if k in a and isinstance(a[k], dict) and isinstance(v, dict):
            deep_merge(a[k], v)
        else:
            a[k] = v
    return a

Explanation

Python provides multiple dictionary merge methods; 3.9+ supports the pipe operator.

More Python Snippets