Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 24, 2022 09:13 pm

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.



Original Link: https://code.tutsplus.com/tutorials/how-to-merge-two-python-dictionaries--cms-26230

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code