如何检查字典是否为空?

696 投票
8 回答
1076449 浏览
提问于 2025-04-18 03:27

我正在尝试检查一个字典是否为空,但它的表现不太正常。它直接跳过了这个检查,只显示了在线,除了这个消息之外什么都没有。有人知道这是为什么吗?

def isEmpty(self, dictionary):
    for element in dictionary:
        if element:
            return True
        return False

def onMessage(self, socket, message):
    if self.isEmpty(self.users) == False:
        socket.send("Nobody is online, please use REGISTER command" \
                 " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))    

8 个回答

9

字典可以自动转换成布尔值,空字典会被认为是 False,而非空字典则被认为是 True

if myDictionary: non_empty_clause()
else: empty_clause()

如果你觉得这样太复杂了,也可以用 len(myDictionary) 来检查字典的长度是否为零,或者用 set(myDictionary.keys()) 来检查是否是一个空集合,或者直接用 {} 来比较。

isEmpty 函数不仅没有必要,而且你的实现中还有几个明显的问题。

  1. return False 这一行的缩进太深了。它应该在 for 循环外面,和 for 语句在同一层级。这样的话,如果字典里有键,代码只会处理一个随机选择的键。如果字典里没有键,函数会返回 None,这会被当作布尔值的 False。这样一来,所有空字典都会被错误地判断为“假阴性”。
  2. 如果字典不为空,代码只会处理一个键,并返回这个键对应的值的布尔值。你甚至不能保证每次调用时都是同一个键。所以会出现“假阳性”的情况。
  3. 假设你把 return False 的缩进修正到 for 循环外面,那么你得到的就是所有键的布尔值的“或”运算,或者如果字典为空则返回 False。但你仍然会有“假阳性”和“假阴性”的问题。请进行修正,并用下面的字典进行测试以验证。

myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}

28

下面是检查一个空字典的简单方法:

a = {}
  1. if a == {}:
      print ('empty dict')
    
  2. if not a:
      print ('empty dict')
    

方法1比较严格,因为当 a = None 时,方法1会给出正确的结果,而方法2则会给出错误的结果。

36
d = {}
print(len(d.keys()))

如果长度是零,那就说明这个字典是空的。

227

这里有三种方法可以检查字典是否为空。不过我个人更喜欢第一种方法,其他两种方法说得太复杂了。

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool(test_dict):
    print "Dict is Empty"


if len(test_dict) == 0:
    print "Dict is Empty"
1196

在Python中,空字典会被认为是 False

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

所以,你的 isEmpty 函数其实是多余的。你只需要做的是:

def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

撰写回答