这是我最初的字典目录
[{"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
这是带有defaultdict的sameple代码
您可以使用^{} ,或者只使用} 方法,即更改以下行:
dict
类的^{到
相关问题 更多 >
编程相关推荐