Python:检查字典是否为空的高效方法 [英] Python:Efficient way to check if dictionary is empty or not

查看:1875
本文介绍了Python:检查字典是否为空的高效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字典是否为空?更具体地说,我的程序从字典中的一些键开始,我有一个循环,循环,直到字典中有键。总体算法是这样的:


从dict中的某些键开始

,而dict中有键

在dict的第一个键上执行一些操作

删除第一个键


请注意一些操作在上面的循环中可能会添加新的键到字典。
我试过
为key,d.iteritems()中的值



但是在while循环中添加了一些新的密钥,它是失败的。

解决方案

any(d) / code>



如果该字符串将返回true。 d至少包含一个密钥,否则为false。



示例:



any({0:'test'})==另一个(更一般的)方法是检查键的nbr。



> len(d.keys())


How to check if dictionary is empty or not? more specifically, my program starts with some key in dictionary and I have a loop which iterates till there are key in dictionary. Overall algo is like this:

Start with some key in dict
while there is key in dict
do some operation on first key in dict
remove first key

Please note that some operation in above loop may add new keys to dictionary. I've tried for key,value in d.iteritems()

but it is failing as during while loop some new key are added.

解决方案

any(d)

This will return true if the dict. d contains at least one truelike key, false otherwise.

Example:

any({0:'test'}) == False

another (more general) way is to check the nbr of keys

len(d.keys())

这篇关于Python:检查字典是否为空的高效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆