Python:检查字典是否为空的有效方法

use*_*567 33 python dictionary

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

从dict中的某个键开始,
当dict中有键时,
在dict
中的第一个键上执行某些操作,删除第一个键

请注意,some operation在上面的循环中可能会添加新的键到字典.我试过了 for key,value in d.iteritems()

但它失败了,因为在while循环期间添加了一些新密钥.

Waj*_*jih 40

any(d)

如果dict,这将返回true.d包含至少一个truelike键,否则为false.

例:

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

另一种(更一般的)方法是检查物品的数量:

len(d)

  • 这不对.`any(d)`如果d包含至少一个truelike键,则返回True.但是如果键是假的 - 例如,`d = {0:'这个字典不是空'}` - 那么`any(d)`将是False. (44认同)
  • 根据http://docs.python.org/2/library/functions.html#any,这是正确的解决方案 (2认同)

Jam*_*arp 16

这样做:

while d:
    k, v = d.popitem()
    # now use k and v ...
Run Code Online (Sandbox Code Playgroud)

布尔上下文中的字典如果为空则为False,否则为True.

字典中没有"第一"项,因为字典不是有序的.但是popitem每次都会删除并返回一些项目.


小智 16

我只是想知道我是否打算首先尝试从中获取数据的字典,这似乎是最简单的方法.

d = {}

bool(d)

#should return
False

d = {'hello':'world'}

bool(d)

#should return
True
Run Code Online (Sandbox Code Playgroud)


Edu*_*ana 15

只需查看字典:

d = {'hello':'world'}
if d:
  print 'not empty'
else:
  print 'empty'

d = {}
if d:
  print 'not empty'
else:
  print 'empty'
Run Code Online (Sandbox Code Playgroud)


Pav*_*yak 7

我会说这种方式更加pythonic并且适合在线:

如果只需要使用函数检查值:

if filter( your_function, dictionary.values() ): ...

当您需要知道您的dict是否包含任何键时:

if dictionary: ...

无论如何,在这里使用循环不是Python方式.