Menu Close

How to merge several Python dictionaries?

Sometimes, we want to merge several Python dictionaries.

In this article, we’ll look at how to merge several Python dictionaries.

How to merge several Python dictionaries?

To merge several Python dictionaries, we can use the ** operator to unpack dictionary entries into another dictionary.

For instance, we write:

a = {'a': 1, 'b': 2, 'c': 3}
b = {'d': 1, 'e': 2, 'f': 3}
c = {1: 1, 2: 2, 3: 3}
merge = {**a, **b, **c}
print(merge)

to merge the entries of a, b, and c into the merge dictionary by unpacking the entries from a, b, and c with the ** operator.

Therefore, merge is {'a': 1, 'b': 2, 'c': 3, 'd': 1, 'e': 2, 'f': 3, 1: 1, 2: 2, 3: 3}.

Conclusion

To merge several Python dictionaries, we can use the ** operator to unpack dictionary entries into another dictionary.

Posted in Python, Python Answers