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}
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}
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}
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}
Merge and overwrite key:
merged = {**dict1, **dict2, **dict3, "a": 10}
print(merged) # {'a': 10, 'b': 2, 'c': 3, 'd': 4, 'x': 5, 'y': 6}
Top comments (1)
It don't keeps duplicate items.
I need to keep duplicate items.