How to Merge Two Python Dictionaries

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:

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:

In which case, you will get the following output:

If you were to instead merge books1 into books2 as in the following code:

You would get a rearranged dictionary as output:

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 books1could 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:

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:

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:

This code will also give the desired output:

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 (**):

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:

Now running the code will give you the desired output:

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):

The output in this case will be:

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

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:

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:

In which case, you will get the following output:

If you were to instead merge books1 into books2 as in the following code:

You would get a rearranged dictionary as output:

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 books1could 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:

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:

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:

This code will also give the desired output:

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 (**):

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:

Now running the code will give you the desired output:

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):

The output in this case will be:

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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » How to Merge Two Python Dictionaries." Abder-Rahman Ali | Sciencx - Wednesday March 23, 2016, https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/
HARVARD
Abder-Rahman Ali | Sciencx Wednesday March 23, 2016 » How to Merge Two Python Dictionaries., viewed ,<https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/>
VANCOUVER
Abder-Rahman Ali | Sciencx - » How to Merge Two Python Dictionaries. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/
CHICAGO
" » How to Merge Two Python Dictionaries." Abder-Rahman Ali | Sciencx - Accessed . https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/
IEEE
" » How to Merge Two Python Dictionaries." Abder-Rahman Ali | Sciencx [Online]. Available: https://www.scien.cx/2016/03/23/how-to-merge-two-python-dictionaries/. [Accessed: ]
rf:citation
» How to Merge Two Python Dictionaries | Abder-Rahman Ali | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.