本文介绍了在字典列表中组合相同键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下格式的字典列表:
I have a list of dictionaries in the following format:
foo = [
{'a': 'x', 'b': 'y', 'c': 'z'},
{'a': 'j', 'c': 'z'}
]
我想将此字典列表分组为一个字典,例如:
I want to group this list of dictionaries into a single dictionary, like:
bar = {
'a': ['x', 'j'],
'b': ['y', None],
'c': ['z', 'z']
}
我目前所做的是,循环遍历 foo
中的所有 dicts 并创建一个键列表,然后再次循环以创建 bar
.我想知道是否有更简单的方法来实现这一点.有人可以帮忙吗?
What I've currently done is, looping through all the dicts in foo
and create a list of keys and then looping again over the same to create bar
. I wonder whether there is a simpler way to accomplish this. Can anyone help?
推荐答案
bar = {
k: [d.get(k) for d in foo]
for k in set().union(*foo)
}
谷歌的东西:
- python 列表理解
- python 字典理解
- 巨蟒之星
- python 字典获取
- python 集合联合
这篇关于在字典列表中组合相同键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!