Merge Dictionary in Python

There are two methods but I’ll focus on one that is a trick which merges two dictionaries and creates a new one using the ** character to pass multiple arguments using the dictionary:

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}


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

Since both keys have the same b key, the last dictionary is considered and added to the resulting merge. In other words, if there are duplicates, the duplicate in the first dictionary is replaced by the duplicate in the second one.

Leave a Reply