IlConte
IlConte

Reputation: 159

Merge many dicts in one

In Python 3.7.2 I have this output from a for loop:

{'London': {'House': 1800.00}}
{'London': {'Farm': 2500.0}}
{'Rome': {'House': 1500.00}}
{'Rome': {'Farm': 3000.00}}

I want to get this at last loop:

{ 'London': 
    { 'House': 1800.00,
      'Farm': 2500.00
    },
  'Rome': 
    { 'House': 1500.00,
      'Farm': 3000.00
    },
}

I've tried many solutions as .update() and more, but I don't get the right way.

For example this solution override the first couple key value (as for .update() method):

dict(list(self.PRICE_LIST.items()) + list(price_location.items()))

{
    "London": {
        "Farm": 2500.00
    },
    "Rome": {
        "Farm": 3000.00
    },
}

Upvotes: 2

Views: 86

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Use list comprehension:

>>> [{list(dicts[i].keys())[0]:dict(list(dicts[i].values())[0].items()|list(dicts[i+1].values())[0].items())} for i in range(0,len(dicts),2)]
[{'London': {'House': 1800.0, 'Farm': 2500.0}}, {'Rome': {'Farm': 3000.0, 'House': 1500.0}}]
>>> 

Upvotes: 0

Martin Ueding
Martin Ueding

Reputation: 8709

You need a loop and update the nested values one at a time:

import collections
import pprint

dicts = [
    {'London': {'House': 1800.00}},
    {'London': {'Farm': 2500.0}},
    {'Rome': {'House': 1500.00}},
    {'Rome': {'Farm': 3000.00}},
]

merged = collections.defaultdict(dict)

for d in dicts:
    for key, val in d.items():
        merged[key].update(val)

pprint.pprint(dict(merged))

Output then is this:

{'London': {'Farm': 2500.0, 'House': 1800.0},
 'Rome': {'Farm': 3000.0, 'House': 1500.0}}

Upvotes: 2

Related Questions