Python - 检查字典是否为空


在分析数据集时,我们可能会遇到必须处理空字典的情况。在本文中,我们将学习如何检查字典是否为空。

使用 if

如果字典中有元素,if 条件将变为 true。否则,它将变为 false。所以,在下面的程序中,我们将仅使用 if 条件检查字典的空情况。

示例

 动态演示

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
   print("dict1 is not empty")
else:
   print("dict1 is empty")
if dict2:
   print("dict2 is not empty")
else:
   print("dict2 is empty")

输出

运行上面的代码将得到以下结果 −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty

使用 bool()

如果字典不为空,则 bool 方法将变为 true。否则,它将变为 false。所以,我们在表达式中使用它来打印字典是否为空的结果。

示例

 动态演示

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2))

输出

运行上面的代码将得到以下结果 −

The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False

更新于: 03-Mar-2020

6K+ 浏览

开启你的 \职业生涯

通过完成课程获得认证

立即开始
广告
© . All rights reserved.