我试图检查字典是否为空,但它不能正常工作。它只是跳过它并显示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()))    

当前回答

test_dict = {}
if not test_dict.keys():
    print "Dict is Empty"

其他回答

test_dict = {}
if not test_dict.keys():
    print "Dict is Empty"

你也可以使用get()。最初我认为它只是检查是否存在密钥。

>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True

我喜欢get的原因是它不会触发异常,因此可以轻松遍历大型结构。

在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()))
d = {}
print(len(d.keys()))

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

1号路

len(given_dic_obj) 

如果没有元素,则返回0。 Else返回字典的大小。

2号路

bool(given_dic_object)

如果字典为空则返回False,否则返回True。