2

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
    },
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
IlConte
  • 150
  • 1
  • 2
  • 9
  • 1
    Possible duplicate of [merging several python dictionaries](https://stackoverflow.com/questions/9415785/merging-several-python-dictionaries) – Nazim Kerimbekov Feb 24 '19 at 09:59

2 Answers2

2

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}}
Martin Ueding
  • 8,245
  • 6
  • 46
  • 92
0

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}}]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114