阅读 563

Python-检查字典是否为空

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

使用if

如果字典中包含元素,则if条件的值为true。否则,它将评估为false。因此,在下面的程序中,我们将仅使用if条件检查字典的空度。

示例

dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}# Given dictionariesprint("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))# Check if dictionary is emptyif 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 dictionariesprint("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))# Check if dictionary is emptyprint("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? : TrueIs dict2 empty? : False


文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐