1

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.

uber
  • 4,163
  • 5
  • 26
  • 55

1 Answers1

2

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}}
yvesonline
  • 4,609
  • 2
  • 21
  • 32
  • seems to work! care to explain what you did? mainly what the two asterisks do. – uber Feb 19 '21 at 13:03
  • Good to hear! It's a combination of dictionary comprehensions (see [Python doc](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)) and using the `**` operator to dump the key/value pairs from one dictionary into the new dictionary. Feel free to [vote and accept](https://stackoverflow.com/help/someone-answers). – yvesonline Feb 19 '21 at 13:07
  • how would this be different if there were 3 dictionaries to merge? – uber Feb 19 '21 at 18:57
  • 1
    You can merge it in one go with the others like that: `merged_dict = {k: { **dict_1[k], **dict_2[k], **dict_3[k] } for k in dict_2.keys()}` (this is still assuming they all have the same keys). – yvesonline Feb 20 '21 at 12:54