- Python | Add dictionary to dictionary without overwriting
- Add dictionary to dictionary without overwriting in Python.
- Frequently Asked:
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- How to Merge Dictionaries in Python
- How to Merge Dictionaries in Python Using a For Loop
- How to Merge Dictionaries in Python Using the dict.update() Method
- How to Merge Dictionaries in Python Using the ** operator
- How to Merge Dictionaries in Python Using the | Operator
- Conclusion
Python | Add dictionary to dictionary without overwriting
In this article, we will discuss how to add the contents of a dictionary to another dictionary without overwriting values of similar keys.
Suppose we have two dictionaries with some similar keys. Like this,
dict_1 and dict_2 have following common keys – ‘test’, ‘at’, ‘Hello’. Now we want to add the contents of a dictionary dict_2 to dictionary dict_1. But instead of overwriting values for common keys, we want to merge the values of common keys while adding. For example, after adding the contents of dict_2 to dict_1, the final content of dict_1 should be like this,
Values of similar keys from both the dictionaries should persist in a list after merging. Let’s see how to do that,
Add dictionary to dictionary without overwriting in Python.
Directly calling the dictionary’s update() function with another dictionary as a argument i.e. dict_1.update(dict_2), will update the existing values of common key. So, instead of it, we will do the following steps,
Frequently Asked:
- Iterate over all key-value pairs of dictionary dict_2 in a loop
- During iteration, for each key-value pair, check if key already exist in dictionary dict_1 or not.
- If the key already exists in dict_1 and the value for that key is not of list type, create a list and add both values of that key from dict_1 & dict_2 to it. Then replace the current value of that key in dict_1 with this list.
- If the key already exists in dict_1 and it is has a value of list type. Then append the value of this key from dict_2 to that list value in dict_1.
- If the key doesn’t exist in dict_1, then add this key-value pair to dict_1.
Let’s understand by an example,
dict_1 = < "Hello": 56, "at": 23, "test": 43, "this": 12 >dict_2 = < 'test': 4, 'at': 5, 'why': 6, 'Hello': 20 >for key, value in dict_2.items(): if key in dict_1: if isinstance(dict_1Python append two dict, list): dict_1Python append two dict.append(value) else: temp_list = [dict_1Python append two dict] temp_list.append(value) dict_1Python append two dict = temp_list else: dict_1Python append two dict = value print(dict_1)
Here, we added all the key-value pairs of dictionary dict_2 to another dictionary dict_1. Both dict_1 and dict_2 had similar keys, and for those keys, the values from dict_2 got added along with the existing values from dict_1. So, nothing got overwritten while adding a dictionary to another dictionary.
We learned a way to all contents of a dictionary to another dictionary without overwriting the values of similar keys.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
How to Merge Dictionaries in Python
Ashutosh Krishna
In Python, a dictionary is a collection you use to store data in pairs. It is ordered and mutable, and it cannot store duplicate data.
We write a dictionary using curly brackets like this:
Sometimes, we need to merge two or more dictionaries to create a bigger dictionary. For example:
dict_one = < "id": 1, "name": "Ashutosh", "books": ["Python", "DSA"] >dict_two = < "college": "NSEC", "city": "Kolkata", "country": "India" >merged_dict =
In the merged_dict we have the key-value pairs of both dict_one and dict_two . This is what we wish to achieve programmatically.
There are various ways we can do this in Python:
- Using a for loop
- Using the dict.update() method
- Using the ** operator
- Using the | (Union) operator (for Python 3.9 and above)
Let’s explore each way one after another.
How to Merge Dictionaries in Python Using a For Loop
We can merge two or more dictionaries using for loop like this:
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> for key,value in dict_two.items(): . merged_dictPython append two dict = value . >>> merged_dict >>> for key,value in dict_three.items(): . merged_dictPython append two dict = value . >>> merged_dict
But the problem with this method is that we need to run so many loops to merge the dictionaries.
How to Merge Dictionaries in Python Using the dict.update() Method
If you explore the dict class, there are various methods inside it. One such method is the update() method which you can use to merge one dictionary into another.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . "books": ["Python", "DSA"] . >>>> dict_two = < . "college": "NSEC", . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one
But the problem when we use the update() method is that it modifies one of the dictionaries. If we wish to create a third dictionary without modifying any of the other dictionaries, we cannot use this method.
Also, you can only use this method to merge two dictionaries at a time. If you wish to merge three dictionaries, you first need to merge the first two, and then merge the third one with the modified dictionary.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> dict_one.update(dict_two) >>> dict_one >>> dict_one.update(dict_three) >>> dict_one
Let’s explore some other options.
How to Merge Dictionaries in Python Using the ** operator
You can use the double-asterisk (**) method to unpack or expand a dictionary like this:
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"] . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = <**dict_one, **dict_two, **dict_three>>>> merged_dict
Using the ** operator to merge the dictionaries doesn’t affect any of the dictionaries.
How to Merge Dictionaries in Python Using the | Operator
Starting with Python 3.9, we can use the Union ( | ) operator to merge two or more dictionaries.
>>> dict_one = < . "id": 1, . "name": "Ashutosh", . >>>> dict_two = < . "books": ["Python", "DSA"], . "college": "NSEC", . >>>> dict_three = < . "city": "Kolkata", . "country": "India" . >>>> merged_dict = dict_one | dict_two | dict_three >>> merged_dict
This is the most convenient method available for merging dictionaries in Python.
Conclusion
We have explored several different methods for merging dictionaries. If you have Python 3.9 or above, you should use the | operator. But if you use older versions of Python, you can still use the other methods discussed above.
Ashutosh Krishna
Application Developer at Thoughtworks India
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.