Python

Merge two dictionaries in Python (2.7)

Disclaimer:
This matter is extent. There are a number of different ways to do the same thing. My goal is to have an easy-to-do shortcut at hand to use it when I need it. See a link below for the source article with more information and discussion on the topic.

Dictionaries to be merged into a third one, z:

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

To merge them:

>>> z = x.copy()
>>> z.update(y)

which returns:

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

Note that the value of 'b' was the last one updated, coming from the y dictionary.

For further details on this topic, please visit the source article at Stack Overflow.

Thanks!

Advertisements