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

2024-09-29 01:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我最初的字典目录

[{"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


Tags: 字典englishagolanguagerowcountrycodepercentagespanish
2条回答

这是带有defaultdict的sameple代码

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 

您可以使用^{},或者只使用dict类的^{}方法,即更改以下行:

language_dict[key1][key2] = row

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

相关问题 更多 >