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 = {  "Hello": 56,
            "at": 23,
            "test": 43,
            "this": 12 }

dict_2 = {  'test': 4,
            'at': 5,
            'why': 6,
            'Hello': 20 }

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,

{'Hello': [56, 20],
 'at'   : [23, 5],
 'test' : [43, 4],
 'this' : 12,
 'why'  : 6}

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,

  • 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_1[key], list):
            dict_1[key].append(value)
        else:
            temp_list = [dict_1[key]]
            temp_list.append(value)
            dict_1[key] = temp_list
    else:
        dict_1[key] = value


print(dict_1)

Output:

{'Hello': [56, 20],
 'at'   : [23, 5],
 'test' : [43, 4],
 'this' : 12,
 'why'  : 6}

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.

Summary:

We learned a way to all contents of a dictionary to another dictionary without overwriting the values of similar keys.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top