首页 > 解决方案 > 消除由列表和数组组成的python dict中的空值

问题描述

我想从 dict 中消除所有空值,其值是列表和 nd 数组的混合。所以我尝试了:

    res = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele]

但我得到了错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). And if I try:

AttributeError: 'list' object has no attribute 'any' 

我得到错误

AttributeError: 'list' object has no attribute 'any'

所以我想知道是否有更通用的方法来删除 python 中的空值dict

标签: pythonarrayslistdictionary

解决方案


我认为您使这一步比必要的复杂(并且不包括完整的示例!)

下面的示例创建一个新的字典res,其中的所有值test_dict都具有非空值。我len()在这里使用,因为它适用于列表和 nd 数组。对于列表,我会省略调用len()并仅使用val.

test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if len(val)}

如果您想使用 any(),您会发现 dict 值是包含至少一个真实项目的列表:

test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if any(val)}

推荐阅读