DEV Community

Bo
Bo

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

Oldest comments (1)

Collapse
 
shahvipul15 profile image
shah vipul

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

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.