0

我有一个嵌套的默认字典,如下所示:

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

如何将上述嵌套字典转换为如下记录列表glom

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

我看过https://glom.readthedocs.io/en/latest/tutorial.html#data-driven-assignment,但我仍然很难过。

4

1 回答 1

0

我不认为你需要一个包。只需一个列表理解就足够了。

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()]

(您需要 python 3.5+ 进行通用解包**info。)

输出:

[{'country': 'China',  'city': 'Beijing', 'num_persons': 1454324, 'num_cars': 134},
 {'country': 'Greece', 'city': 'Athens',  'num_persons': 2332,    'num_cars': 12}]
于 2021-11-02T04:55:32.870 回答