This content originally appeared on Envato Tuts+ Tutorials and was authored by Abder-Rahman Ali
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. Before we commence, I recommend that you open this online Python IDE to run the following code blocks and see the results.
Using The update()
Method
Let's say we have the following two dictionaries:
books1 = {1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'} books2 = {4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript'}
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 dictionary books2
into books1
, include and run the following code in your Python IDE:
books1.update(books2) print(books1)
In which case, you will get the following output:
{1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually', 4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript'}
If you were to instead merge books1
into books2
as in the following code:
books1 = {1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'} books2 = {4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript'} books2.update(books1) print(books2)
You would get a rearranged dictionary as output:
{4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript', 1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'}
However, there's an issue with 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, books1.update(books2)
, the original version of books1
could be modified, and in the latter case, books2.update(books1)
, the original version of books2
could be modified.
For example, consider the following rearranged dictionaries:
books1 = {1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'} books2 = {3: 'JavaScript and jQuery', 4: 'Simplifying JavaScript'} books1.update(books2) print(books1)
As you may have observed, both dictionaries share the same key, which is 3
.
In this case, the first instance (that is, 'Learn JavaScript Visually') will be discarded, so the following will be outputted:
{1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'JavaScript and jQuery', 4: 'Simplifying JavaScript'}
We'll learn about a way to avoid this behavior later on.
Passing All Items to a New Dictionary in a for
Loop
You can also merge two dictionaries using a Python for
loop.
In this case, we'll assign an empty dictionary to a variable—which I call updatedBooks
—and then for every time we iterate over both dictionaries (that is, books1
and books2
), we want to assign the key and value of the respective dictionary items to the empty dictionary: updatedBooks
.
Here's the code for that:
books1 = {'1st': 'You Dont Know JS', '2nd': 'Eloquent JavaScript', '3rd': 'Learn JavaScript Visually'} books2 = {'4th': 'JavaScript and jQuery', '5th': 'Simplifying JavaScript'} updatedBooks = dict() for dict in (books1, books2): for key, value in dict.items(): updatedBooks[key] = value print(updatedBooks)
This code will also give the desired output:
{1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually', 4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript'}
Merging Two Dictionaries in a Single Expression With Double Asterisks
Another method you can use to merge two dictionaries, where you can perform such a task in a single expression, is with the double asterisks operator (**
):
books1 = {1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'} books2 = {4: 'JavaScript and jQuery', 5: 'Simplifying JavaScript'} updatedBooks = dict(books1, **books2) print(updatedBooks)
The double asterisks signals that we want to merge the dictionary books2
into books1
.
Running this code will give you a TypeError: keywords must be string
message. For this code to work, you must change the keys to strings:
books1 = {'1st': 'You Dont Know JS', '2nd': 'Eloquent JavaScript', '3rd': 'Learn JavaScript Visually'} books2 = {'4th': 'JavaScript and jQuery', '5th': 'Simplifying JavaScript'} updatedBooks = dict(books1, **books2) print(updatedBooks)
Now running the code will give you the desired output:
{'1st': 'You Dont Know JS', '2nd': 'Eloquent JavaScript', '3rd': 'Learn JavaScript Visually', '4th': 'JavaScript and jQuery', '5th': 'Simplifying JavaScript'}
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 books1 = {1: 'You Dont Know JS', 2: 'Eloquent JavaScript', 3: 'Learn JavaScript Visually'} books2 = {3: 'JavaScript and jQuery', 4: 'Simplifying JavaScript'} updatedBooks = defaultdict(list) for k, v in chain(books1.items(), books2.items()): updatedBooks[k].append(v) for k, v in updatedBooks.items(): print(k, v)
The output in this case will be:
1 ['You Dont Know JS'] 2 ['Eloquent JavaScript'] 3 ['Learn JavaScript Visually', 'JavaScript and jQuery'] 4 ['Simplifying JavaScript']
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.
This post has been updated with contributions from Kingsley Ubah. Kingsley is passionate about creating content that educates and inspires readers. Hobbies include reading, football and cycling.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Abder-Rahman Ali
Abder-Rahman Ali | Sciencx (2016-03-23T10:15:43+00:00) How to Merge Two Python Dictionaries. Retrieved from https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.