Merge two dicts with the same keys but add as another value (not replace)

Viewed 63

This seems to shown an example of appending to an array, not adding another value to a dict.

dict_1 = {a: {price: 4000}, b: {price: 14000} }

dict_2 = {a: {discount: 0100}, b: {discount: 0400} }

I would like to merge them to be:

merged_dict: { a: {
                   price: 4000, 
                   discount: 0100
                  }, 
               b: {
                   price: 14000, 
                   discount: 0400
               } 
              }

How to achieve that? Both dictionaries will always have the same keys.

1 Answers

A dictionary comprehension will solve this (I correctly formatted your dictionary definitions from the question, tested with Python 3.8.0):

>>> dict_1 = {'a': {'price': 4000}, 'b': {'price': 14000} }
>>> dict_2 = {'a': {'discount': 100}, 'b': {'discount': 400} }
>>> merged_dict = {k: { **dict_1[k], **dict_2[k] } for k in dict_2.keys()}
>>> merged_dict
{'a': {'price': 4000, 'discount': 100}, 'b': {'price': 14000, 'discount': 400}}
Related