python: how to merge two dictionaries

Let us suppose two dictionaries storing ages of different individuals:

list1 = {"Pierre": 28, "Jeanne": 27}
list2 = {"Marc": 32, "Helene": 34}

If you do mind losing the contents of either list1 or list2 variable, you can update one of the other as follows:


Now list1 variable contains:

{"Pierre": 28, "Jeanne": 27, "Marc": 32, "Helene": 34}

while list2 is unchanged.

Usually, this is not what you want though. Instead, you would prefer to create a third variable keeping list1 and list2 unchanged.

In Python 3.5 or greater, you can use the following syntax:

fulllist = {**list1, **list2}

In Python 2 or 3.4 and below, you need to copy one of the variable and update it:

full_list = list1.copy()  # this keeps list1 unchanged
full_list.update(list2)   # inplace update of the variable full_list

The second method is more generic and would be more backward compatible (if you plan to provide your code to Python 2 users. Indeed, it would work for Python 2 and 3. However, it would be slower for Python 3.5 users (and above).

Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *