如何检查列表的字典是否为空?

时间:2020-11-09 10:44:34

标签: python dictionary

这个想法是要检查dict内部列表中的以下dict是否为空。

例如,以下命令

expected_false={"all_dict": [{"A": [1], "B": [], "C": [], "D": []}]}

应返回空值,因为键“ A”的值为1。

而以下内容应返回空值

expected_empty={"all_dict": [{"A": [], "B": [], "C": [], "D": []}]}

我尝试了以下代码,但是它给出的内容与我的想法有所不同。

all(not d for d in expected_true['all_dict'][0])

3 个答案:

答案 0 :(得分:2)

any(len(item) for item in expected_true['all_dict'][0].values())

答案 1 :(得分:1)

这应该有效:

print(not any(len(expected_false['all_dict'][x]) > 0 for x in expected_false['all_dict']))

答案 2 :(得分:0)

字典是一组键值对。 伪代码:

-Get value of 'all_dict' key inside of dictionary that named {expected_false}
-That 'all_dict' key has a value which is a list that contains only one item (which is an another dictionary)
-To address list item : ['all_dict'][0] (we reached first list item, which is a dictionary)
-Use dict.values() method to get all values of keys innermost dictionary
-And each of these values are also list by itself

expected_false['all_dict'][0].values()

因此,以上代码返回列表。并检查每个列表中是否有任何项目。然后打印结果。

expected_false={"all_dict": [{"A": [1], "B": [], "C": [], "D": []}]}
for item in expected_false['all_dict'][0].values():
    if len(item)!=0:
        a=any(item)
        print(a)