Introduction
It's not uncommon to have two dictionaries in Python which you'd like to combine. When merging dictionaries, we have to consider what will happen when the two dictionaries have the same keys. But first, we have to define what should happen when we merge.
In this article, we will take a look at various ways on how to merge two dictionaries in Python. Some solutions are not available to all Python versions, so we will examine ways to merge for selected releases too.
Merging Dictionaries in Python
Merges usually happen from the right to left, as dict_a <- dict_b
. When there's a common key holder in both the dictionaries, the second dictionary's value overwrites the first dictionary's value.
This can be demonstrated in the illustration given below, where the components of the dictionary B gets merged to A, with the green suit of dictionary B taking the place of the orange suit:
Throughout this article, we will be using the following dictionaries.
- Dictionaries with values:
>>> a = {1:'peanut', 2:'butter', 3:'jelly', 4:'time'}
>>> b = {1:'fish', 2:'chips'}
- Dictionaries with nested values:
>>> c = {1: ['peanut','butter','jelly','time'], 2:['fish','chips']}
>>> d = {1: ['fish','chips'], 2:['peanut','butter','jelly','time']}
Using the Merge Operator | (Python 3.9 and Above)
From Python version 3.9 onward, we can use the merge operators (represented by |
) to combine two dictionaries:
>>> x = a | b
>>> print(x)
{1: 'fish', 2: 'chips', 3: 'jelly', 4: 'time'}
The dictionary merge operators can also be used in the place of nested dictionaries too. Here, the complete overwrite of the value of the matching key takes place:
>>> y = c | d
>>> print(y)
{1: ['fish', 'chips'], 2: ['peanut', 'butter', 'jelly', 'time']}
Using Dict Unpacking (Python 3 and Above)
For earlier versions of Python 3, we're unfortunately unable to use the merge operators. Instead, we can merge by unpacking both the dictionaries, using the **
double asterisks, inside another dictionary:
>>> x = {**a, **b}
>>> print(x)
{1: 'fish', 2: 'chips', 3: 'jelly', 4: 'time'}
The same applies to the dictionaries with the nested list values. The values of the overlapping keys will be overwritten:
>>> y = {**c, **d}
>>> print(y)
{1: ['fish', 'chips'], 2: ['peanut', 'butter', 'jelly', 'time']}
Python 2 and Above
In legacy Python versions, the snippets above will not work. Instead, the merge can be facilitated by combining the items of the dictionary, or dict_items
of both variables.
We can also use the copy()
and update()
dictionary methods. Lastly, we can loop through a dictionary's items and use the extend()
method to add it to another dictionary.
Using items()
Let's begin by combining with items()
:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
>>> x = dict(a.items() + b.items())
>>> print(x)
{1: 'fish', 2: 'chips', 3: 'jelly', 4: 'time'}
The syntax above holds good for simple values. For a nested dictionary containing list values, the items()
call needs to be cast to a list()
and then combined:
>>> y = dict(list(c.items()) + list(d.items()))
>>> print(y)
{1: ['fish', 'chips'], 2: ['peanut', 'butter', 'jelly', 'time']}
This solution works well because the keys were numerical, the original keys were preserved. For keys of different types, you would prefer the following option.
Using Dictionary update()
Another way to perform the merge is to copy one of the dictionaries and update it with the other:
>>> x = a.copy()
>>> x.update(b)
>>> print (x)
{1: 'fish', 2: 'chips', 3: 'jelly', 4: 'time'}
Appending List Values in All Python Versions
In the previous sections, we have overwritten nested values of the merged dictionaries. There are cases where the nested values need to be appended instead of overwritten. This can be done by using the extend()
method:
>>> for k, v in d.items():
... if k in c:
... c[k].extend(v)
... else:
... c[k] = v
>>>
>>> print(c)
{1: ['peanut', 'butter', 'jelly', 'time', 'fish', 'chips'], 2: ['fish', 'chips', 'peanut', 'butter', 'jelly']}
Conclusion
In this article, we have learned how dictionary merges work, and how we can merge two dictionaries in different versions of Python. Merging dictionaries can be quite handy in situations like reading multiple JSON files, building a map of objects or even building indexes of content.