我试图检查字典是否为空,但它不能正常工作。它只是跳过它并显示ONLINE,除了显示消息之外没有任何其他内容。知道为什么吗?

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()))    

当前回答

在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()))

其他回答

这里有三种方法可以检查dict是否为空。不过我更喜欢使用第一种方法。另外两种方法太啰嗦了。

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"

检查空字典的简单方法如下:

a = {}

如果a == {}: 打印('空字典') 如果不是a: 打印('空字典')

方法1更严格,因为当a = None时,方法1将提供正确的结果,但方法2将给出错误的结果。

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

如果长度为零,则意味着字典为空。

使用“任何”

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

在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()))