python - 从字典中的迭代中删除 "None"

标签 python python-3.x dictionary

我有一个包含各种键和值的字典列表。我正在尝试根据键对其进行分组

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 的任何指导?

Code

最佳答案

尝试 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/

相关文章:

python - 无法从字典引用使用 "vars()[]"创建的变量

Python 回文帮助 : Count palindromes in a sentence

python - 查找列表中连续增加的元素的数量

python - 使用 ssl 访问 kafka 代理时出错

python - Tkinter:为按钮和标签制作 'classes'

python - Scrapy Spider 不返回任何信息

typescript - 正确输入具有绑定(bind)运行功能的 map

python - 向量化python中矩阵中所有组合的角度计算

python - 以 t 开头但以 e 以外的其他词结尾的单词

c# - 在 C# 中获取字典最高值键的好方法