-1

This is an extension of this question. And this seems to show an example of appending to an array, not adding another value to a sub-dict.

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

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

dict_3 = {a: {amount: 41}, b: {amount: 522} }

I would like to merge them to be:

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

How to achieve that? And how would that be if there was en even longer list of dictionaries to merge? The dictionaries will always have the same keys (a, b).

I tried doing the same as in the first hyperlink but the .items() seem to make it unscalable.

uber
  • 4,163
  • 5
  • 26
  • 55
  • 1
    What was the difficulty when you tried to do this? Have you tried writing something like: `for k in dict_1: merged_dict[k]['price'] = dict_1[k]['price']; for k in dict_2: merged_dict[k]['discount'] = dict_2[k]['discount']`, etc.? – mkrieger1 Feb 19 '21 at 19:29
  • I also don't understand what is the difference between this question and your earlier question you've linked, other than here you are showing 3 input dictionaries instead of 2. – mkrieger1 Feb 19 '21 at 19:43
  • ```merged_dict = {k: { **dict_1[k], **dict_2[k] } for k in dict_2.keys()}``` this has two dictionaries, and loops over the keys of the second dict only. I can't think of how to do this, since which dict should I iterate over? – uber Feb 19 '21 at 19:45
  • Over all of them, in another loop? – mkrieger1 Feb 19 '21 at 20:01

1 Answers1

1

You can generalize this kind of merge by placing your dictionaries in a list and creating the merged dictionary in a comprehension:

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

dict_2 = {"a": {"discount": 100}, "b": {"discount": 400} }

dict_3 = {"a": {"amount": 41}, "b": {"amount": 522} }

dicts  = [dict_1, dict_2, dict_3]

merged = { k:dict(kv for d in dicts for kv in d[k].items()) for k in dicts[0] }

print(merged)
{'a': {'price': 4000, 'discount': 100, 'amount': 41}, 
 'b': {'price': 14000, 'discount': 400, 'amount': 522}}
Alain T.
  • 40,517
  • 4
  • 31
  • 51