我有一个包含各种键和值的字典列表。我正在尝试根据键对其进行分组
from itertools import chain, zip_longest
data = [
{'a': 2, 'b': 4, 'c': 3, 'd': 2},
{'b': 2, 'c': 2, 'd': 5, 'e': 4, 'f': 1},
{'a': 2, 'd': 2, 'e': 6, 'f': 5, 'g': 12},
{'b': 2, 'd': 2, 'e': 6, 'f': 6},
{'c': 5, 'e': 33, 'g': 21, 'h': 56, 'i': 21}
]
print(type(data))
bar ={
k: [d.get(k) for d in data]
for k in chain.from_iterable(data)
}
print(bar)
我的输出:
{'a': [2, None, 2, None, None], 'b': [4, 2, None, 2, None],
'c': [3, 2, None, None, 5], 'd':[2, 5, 2, 2, None], 'e': [None, 4, 6, 6, 33],
'f': [None, 1, 5, 6, None], 'g': [None, None, 12, None, 21],
'h': [None, None, None, None, 56], 'i': [None, None, None, None, 21]}
我不想在值中显示“无”
期望的输出:
{'a': [2, 2], 'b': [4, 2, 2], 'c': [3, 2, 5], 'd':[2, 5, 2, 2], 'e': [4, 6, 6, 33],
'f': [1, 5, 6], 'g': [1221], 'h': [56], 'i': [21]}
我也尝试过使用过滤功能,但没有成功。关于如何删除 None 的任何指导?
最佳答案
尝试 this :
from operator import is_not
from functools import partial
{ k: list(filter(partial(is_not, None), v)) for k, v in d.items() }
Input: {'x': [0, 23, 234, 89, None, 0, 35, 9] }
Output: {'x': [0, 23, 234, 89, 0, 35, 9]}
关于python - 从字典中的迭代中删除 "None",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57953011/