DEV Community

BC
BC

Posted on

Merge multiple dictionaries - Python Tips

With Python >= 3.5 we can easily merge multiple dictionaries with {**} operation.

dict1 = {"a":1, "b":2}
dict2 = {"x":3, "y":4}
merged = {**dict1, **dict2}
print(merged) # {'a': 1, 'b': 2, 'x': 3, 'y': 4}
Enter fullscreen mode Exit fullscreen mode

If the latter dictionary contains the same key as the previous one, it will overwrite the value for that key.

dict1 = {"a":1, "b":2}
dict2 = {"x":3, "a":4}
merged = {**dict1, **dict2}
print(merged) # {'a': 4, 'b': 2, 'x': 3}
Enter fullscreen mode Exit fullscreen mode

We can merge several dictionaries:

dict1 = {"a":1, "b":2}
dict2 = {"c":3, "d":4}
dict3 = {"x":5, "y":6}
merged = {**dict1, **dict2, **dict3}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'x': 5, 'y': 6}
Enter fullscreen mode Exit fullscreen mode

And we can add extra keys when do the merging:

merged = {**dict1, **dict2, **dict3, "z":7}
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'x': 5, 'y': 6, 'z': 7}
Enter fullscreen mode Exit fullscreen mode

Merge and overwrite key:

merged = {**dict1, **dict2, **dict3, "a": 10}
print(merged) # {'a': 10, 'b': 2, 'c': 3, 'd': 4, 'x': 5, 'y': 6}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
shahvipul15 profile image
shah vipul

It don't keeps duplicate items.
I need to keep duplicate items.