In a previous tutorial we learned about Python Dictionaries, and saw that they are considered unordered sets with a key/value
pair, where keys are used to access items as opposed to the position, as in lists for instance.
In this quick tip, I'm going to show you how to concatenate (merge) two dictionaries together.
The Update() Method
Let's say we have the following two dictionaries:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3} dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
How can we merge those two dictionaries in a single dictionary? A function we can use in this regard is update([other])
. As stated in the Python documentation:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None
.
update()
accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1, blue=2)
.
So, to merge the above two dictionaries, we can type the following:
dict2.update(dict1)
Say that you typed the following statement in order to view the results:
print dict2.update(dict1)
In this case you will get None
! This is because the update()
function does not return a new dictionary. In order to get the result of the concatenation, simply type the following:
print dict2
In which case, you will get the following output:
{'bookA': 1, 'bookB': 2, 'bookC': 3, 'bookD': 4, 'bookE': 5}
What if we did the following?
dict1.update(dict2) print dict1
In this case, you will get the following output:
{'bookA': 1, 'bookB': 2, 'bookC': 2, 'bookD': 4, 'bookE': 5}
Notice that in the first case, dict2.update(dict1)
, we update the dictionary dict2
with the key/value pairs from dict1
, and overwriting any existing keys. The existent key as we can notice is 'bookC'
, which will have the value 3
in this case, since we are updating with the key/value pairs from dict1
. This will be reversed in the latter case, dict1.update(dict2)
, where we are updating the dictionary dict1
with key/value pairs from dict2
.
However, there's an issue in using update()
to merge two dictionaries. The issue lies in the fact that the original dictionary can be modified. In other words, in the first case for instance, dict2.update(dict1)
, the original version of dict2
could be modified, and in the latter case, dict1.update(dict2)
, the original version of dict1
could be modified. That is to say that you can use update()
to merge two dictionaries if you are not interested in keeping the original version of the dictionary you need to update. By the original version here I mean retaining the value of the key.
Merging Two Dictionaries in a Single Expression
Another method you can use to merge two dictionaries, where you can perform such a task in a single expression, is as follows:
print dict(dict2, **dict1)
The output of this statement is:
{'bookA': 1, 'bookB': 2, 'bookC': 3, 'bookD': 4, 'bookE': 5}
Thus, dict1
overrides dict2
. If we want dict2
to override dict1
, we type:
print dict(dict1, **dict2)
The output in this case would be:
{'bookA': 1, 'bookB': 2, 'bookC': 2, 'bookD': 4, 'bookE': 5}
Retaining Key Values
Returning to the previous issue of keeping the key values, how can we merge two dictionaries while keeping the originals of each dictionary?
A workaround for this can be as follows (taken from the answer in this StackOverflow thread):
from itertools import chain from collections import defaultdict dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3} dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5} dict3 = defaultdict(list) for k, v in chain(dict1.items(), dict2.items()): dict3[k].append(v) for k, v in dict3.items(): print(k, v)
The output in this case will be:
('bookA', [1]) ('bookB', [2]) ('bookC', [3, 2]) ('bookD', [4]) ('bookE', [5])
So, as you can see from this quick tip, it is very easy to merge two dictionaries using Python, and it becomes a bit more complex if we want to retain the values of the same key in each dictionary.
Comments