1

I have a nested default dict that looks like the following:

source["China"]["Beijing"] = {
    "num_persons" : 1454324,
    "num_cars" : 134
}
source["Greece"]["Athens"] = {
    "num_persons" : 2332,
    "num_cars" : 12
}

How do I transform the above nested dict into a list of records like the one below using glom :

result = [
     {
           'country' : 'China',
           'city' : 'Beijing',
           'num_persons' : 1454324,
           'num_cars' : 134
     },
     {
           'country' : 'Greece',
           'city' : 'Athens',
           'num_persons' : 2332,
           'num_cars' : 12
     }
]

I've looked at https://glom.readthedocs.io/en/latest/tutorial.html#data-driven-assignment, but I'm still stumped.

Demeter P. Chen
  • 823
  • 1
  • 7
  • 16

1 Answers1

1

I don't think you need a package for that. Just a list comprehension would suffice.

from collections import defaultdict

source = defaultdict(lambda: defaultdict(dict))
source["China"]["Beijing"] = {"num_persons": 1454324, "num_cars": 134}
source["Greece"]["Athens"] = {"num_persons": 2332, "num_cars": 12}

result = [{'country': country, 'city': city, **info} for country, cities in source.items() for city, info in cities.items()]

(You need python 3.5+ for generalized unpacking **info.)

Output:

[{'country': 'China',  'city': 'Beijing', 'num_persons': 1454324, 'num_cars': 134},
 {'country': 'Greece', 'city': 'Athens',  'num_persons': 2332,    'num_cars': 12}]
j1-lee
  • 13,764
  • 3
  • 14
  • 26