首页 > 解决方案 > 是否有另一种方法可以在 Python 中提取具有复杂/非结构化嵌套 dict 格式的信息?

问题描述

假设我有一个非结构化的嵌套字典,如下所示:

{
'A_brand': {'score1': {'A': 13, 'K': 50}},
'B_brand': {'before_taste': {'score2': {'A': 43, 'D': 23}}, 'after_taste': {'score3': {'H': 36, 'J': 34}}},
'Score4': {'G': 2, 'W': 19}
}

如何获取/显示以下信息:哪个字母的每个分数得分最高?喜欢:

{'key':'value',
'A_brand/score1':'K',
'B_brand/before_taste/score2':'A',
'B_brand/after_taste/score3':'H',
'Score4':'W'}

我所做的是虚拟方式,我创建了一个新的字典并访问每个路径,按值对它们进行排序并选择第一个项目,然后将其添加到新的字典中。例如:

new_csv={'key':'value'}

first=data['A_brand']['before_lunch_break']['score1']
first_new=sorted(first.items(),key=lambda x: x[1],reverse=True)
new_csv['A_brand/score']=first_new[0][0]

second=data['B_brand']['before_taste']['score2']
second_new=sorted(second.items(),key=lambda x: x[1],reverse=True)
new_csv['B_brand/before_taste/score2']=second_new[0][0]

...

我想知道是否有更快或自动的方法来做到这一点?

标签: pythondictionarynested

解决方案


您可以使用带有递归的生成器:

data = {'A_brand': {'score1': {'A': 13, 'K': 50}}, 'B_brand': {'before_taste': {'score2': {'A': 43, 'D': 23}}, 'after_taste': {'score3': {'H': 36, 'J': 34}}}, 'Score4': {'G': 2, 'W': 19}}
def get_max(d, c = []):
   for a, b in d.items():
     if all(not isinstance(i, dict) for i in b.values()): 
        yield ('/'.join(c+[a]), max(b, key=lambda x:b[x]))
     else:
        yield from get_max(b, c+[a])

print(dict(get_max(data)))

输出:

{'A_brand/score1': 'K', 'B_brand/before_taste/score2': 'A', 'B_brand/after_taste/score3': 'H', 'Score4': 'W'}

推荐阅读