Python – 测试空字典值列表
给定一个以列表为值的字典,检查所有列表是否为空。
Input : {“Gfg” : [], “Best” : []}
Output : True
Explanation : Both lists have no elements, hence True.
Input : {“Gfg” : [], “Best” : [4]}
Output : False
Explanation : “Best” contains element, Hence False.
方法 #1:使用 any() + values()
上述功能的组合可以用来解决这个任务。在此,我们检查使用 values() 提取的值中是否存在任何值,如果未找到,则列表为空。
Python3
# Python3 code to demonstrate working of
# Test for Empty Dictionary Value List
# Using any() + values()
# initializing dictionary
test_dict = {"Gfg" : [], "Best" : [], "is" : []}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# checking if any value is found
# using not to negate the result of any()
res = not any(test_dict.values())
# printing result
print("Are value lists empty? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test for Empty Dictionary Value List
# Using all() + values()
# initializing dictionary
test_dict = {"Gfg" : [], "Best" : [], "is" : []}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# checking if all keys have empty list
res = all(ele == [] for ele in list(test_dict.values()))
# printing result
print("Are value lists empty? : " + str(res))
输出
The original dictionary is : {'Gfg': [], 'Best': [], 'is': []}
Are value lists empty? : True
方法 #2:使用 all() + values()
这是我们可以解决问题的另一种方式。在此,我们可以使用 all() 检查每个键是否所有值都为空。
Python3
# Python3 code to demonstrate working of
# Test for Empty Dictionary Value List
# Using all() + values()
# initializing dictionary
test_dict = {"Gfg" : [], "Best" : [], "is" : []}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# checking if all keys have empty list
res = all(ele == [] for ele in list(test_dict.values()))
# printing result
print("Are value lists empty? : " + str(res))
输出
The original dictionary is : {'Gfg': [], 'Best': [], 'is': []}
Are value lists empty? : True