📜  Python|检查字典是否为空

📅  最后修改于: 2022-05-13 01:55:03.826000             🧑  作者: Mango

Python|检查字典是否为空

有时,我们需要检查特定字典是否为空。这个特定的任务在 Web 开发领域有它的应用,我们有时需要测试特定查询的结果或检查我们是否有任何键可以将信息添加到数据库中。让我们讨论可以执行此任务的某些方式。

方法 #1:使用bool()

bool函数可用于执行此特定任务。顾名思义,它执行将对象转换为布尔值的任务,但在这里,传递空字符串会返回 False,因为无法转换为空的内容。

# Python3 code to demonstrate
# Check if dictionary is empty
# using bool()
  
# initializing empty dictionary
test_dict = {}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using bool()
# Check if dictionary is empty 
res = not bool(test_dict)
  
# print result
print("Is dictionary empty ? : " + str(res))
输出 :
The original dictionary : {}
Is dictionary empty ? : True

方法#2:使用not operator

此任务也可以使用检查字典是否存在的 not运算符执行,如果未找到字典中的任何键,则计算结果为 True。

# Python3 code to demonstrate
# Check if dictionary is empty
# using not operator
  
# initializing empty dictionary
test_dict = {}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using not operator
# Check if dictionary is empty 
res = not test_dict
  
# print result
print("Is dictionary empty ? : " + str(res))
输出 :
The original dictionary : {}
Is dictionary empty ? : True