python - 是否有另一种方法可以在 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]
...
我想知道是否有更快或自动的方法来做到这一点?
解决方案
您可以使用带有递归的生成器:
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'}
推荐阅读
- flutter - SelectableText 小部件未在 Web 上显示工具栏
- vb.net - 防止鼠标点击关闭菜单
- .htaccess - 将 apache .htaccess 重写 [B] 标志规则转换为 nginx 时遇到问题
- vba - 使用 sap gui 获取列的总数
- html - Django从表单上传图片
- reactjs - reactjs中history .push和navlink有什么区别
- influxdb - 在特定日期之后获取创建的测量值
- java - java.util.NoSuchElementException: None.get Spark SQL Exception while 从 Mysql 数据库查询并将结果写入 Hadoop
- sql - 如何解决此过程中的此 SQL 错误 (1604)?
- html - Magento 2 事务性电子邮件错误,版权修改