作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下格式的字典:
data = {
'Bob': {
'age': 12,
'weight': 150,
'eye_color': 'blue'
},
'Jim': {
'favorite_food': 'cherries',
'sport': 'baseball',
'hobby': 'running'
},
'Tom': {
'strength': 'average',
'endurance': 'high',
'heart_rate': 'low'
}
}
将 dict 中的所有词典连接成一个新词典的最 Pythonic 方法是什么,这样我最终会得到如下内容:
new_dict = {
'age': 12,
'weight': 150,
'eye_color': 'blue',
'favorite_food': 'cherries',
'sport': 'baseball',
'hobby': 'running',
'strength': 'average',
'endurance': 'high',
'heart_rate': 'low'
}
最佳答案
您可以使用 functools.reduce()
建立结果,一次合并一个字典:
from functools import reduce
data = {
'Bob' : { 'age': 12, 'weight': 150, 'eye_color': 'blue' },
'Jim' : { 'favorite_food': 'cherries', 'sport': 'baseball', 'hobby': 'running' },
'Tom' : { 'strength': 'average', 'endurance': 'high', 'hear_rate': 'low' }
}
result = reduce(lambda x, y: dict(**x, **y), data.values(), {})
print(result)
这个输出:
{'age': 12, 'weight': 150, 'eye_color': 'blue', 'favorite_food': 'cherries',
'sport': 'baseball', 'hobby': 'running', 'strength': 'average',
'endurance': 'high', 'hear_rate': 'low'}
在 Python 3.9 或更高版本上,您可以使用 lambda x: x | y
、operator.or_
或 dict.__or__
而不是 lambda x: dict(**x, **y)
如果您使用的是 Python 3.9 或更高版本。后两个来自Mad Physicist的建议。 .
关于python - 如何将字典的键值对收集到 Python 中的一个大字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71611609/
我是一名优秀的程序员,十分优秀!