如何将常规词典转换为嵌套词典

时间:2020-09-21 06:34:11

标签: python python-3.x

这是我的原始字典列表。

[{"CountryCode":"ABW", "Language":"Dutch", "IsOfficial":"T", "Percentage":5.3},
 {"CountryCode":"ABW", "Language":"English", "IsOfficial":"F", "Percentage":9.5},
 {"CountryCode":"ABW", "Language":"Papiamento", "IsOfficial":"F", "Percentage":76.7},
 {"CountryCode":"ABW", "Language":"Spanish", "IsOfficial":"F", "Percentage":7.4},
 {"CountryCode":"AFG", "Language":"Balochi", "IsOfficial":"F", "Percentage":0.9},
 {"CountryCode":"AFG", "Language":"Dari", "IsOfficial":"T", "Percentage":32.1},
 {"CountryCode":"AFG", "Language":"Uzbek", "IsOfficial":"F", "Percentage":8.8},
 {"CountryCode":"AGO", "Language":"Ambo", "IsOfficial":"F", "Percentage":2.4},
 {"CountryCode":"AGO", "Language":"Chokwe", "IsOfficial":"F", "Percentage":4.2}]

我想将它们转换为嵌套字典(用于加载JSON文件)。喜欢:

{"ABW":{"Dutch":{"IsOfficial":"T", "Percentage":5.3},"English":{"IsOfficial":"F", "Percentage":9.5},"Papiamento":{"IsOfficial":"F", "Percentage":76.7},"Spanish": {"IsOfficial":"F", "Percentage":7.4}},
 "AFG":{"Balochi":{"IsOfficial":"F", "Percentage":0.9},"Dari":{"IsOfficial":"T", "Percentage":32.1},"Uzbek":{"IsOfficial":"F", "Percentage":8.8}},
 "AGO":{"Ambo":{"IsOfficial":"F", "Percentage":2.4},"Chokwe":{"IsOfficial":"F", "Percentage":4.2}}}

我尝试了以下代码,但是它不起作用...

language = json.load(f)
language_dict ={}
for row in language:
    key1 = row.pop('CountryCode',None)
    key2 = row.pop('Language', None)
    language_dict[key1][key2] = row

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用defaultdict,也可以简单地使用dict类的.setdefault()方法,即,更改以下行:

language_dict[key1][key2] = row

language_dict.setdefault(key1, {})[key2] = row

答案 1 :(得分:0)

这是与defaultdict相同的代码

from collections import defaultdict
mylist = [{"CountryCode":"ABW", "Language":"Dutch", "IsOfficial":"T", "Percentage":5.3},
 {"CountryCode":"ABW", "Language":"English", "IsOfficial":"F", "Percentage":9.5},
 {"CountryCode":"ABW", "Language":"Papiamento", "IsOfficial":"F", "Percentage":76.7},
 {"CountryCode":"ABW", "Language":"Spanish", "IsOfficial":"F", "Percentage":7.4},
 {"CountryCode":"AFG", "Language":"Balochi", "IsOfficial":"F", "Percentage":0.9},
 {"CountryCode":"AFG", "Language":"Dari", "IsOfficial":"T", "Percentage":32.1},
 {"CountryCode":"AFG", "Language":"Uzbek", "IsOfficial":"F", "Percentage":8.8},
 {"CountryCode":"AGO", "Language":"Ambo", "IsOfficial":"F", "Percentage":2.4},
 {"CountryCode":"AGO", "Language":"Chokwe", "IsOfficial":"F", "Percentage":4.2}]


res_by_countrycode = defaultdict(dict)
for i in mylist:

    (_, country_value), (_, language_value), IsOfficial, Percentage = i.items() ## this unpack the values
    row = dict([Percentage, IsOfficial]) ## create dict with Percentage and IsOfficial 
    res_by_countrycode[country_value][language_value] = row ## with defaultdict , we can set add key to dict , with regular dict we will get keyRrror
print(dict(res_by_countrycode)) ## print result 
相关问题