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

使用“任何”

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

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

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


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

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

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


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

a = {}

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

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


字典可以自动转换为布尔值,对空字典的值为False,对非空字典的值为True。

if myDictionary: non_empty_clause()
else: empty_clause()

如果这看起来太习惯,您还可以测试len(myDictionary)是否为零,或set(myDictionary.keys())是否为空集,或简单地测试是否与{}相等。

isEmpty函数不仅是不必要的,而且你的实现有多个问题,我可以初步发现。

The return False statement is indented one level too deep. It should be outside the for loop and at the same level as the for statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives. If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives. Let us say you correct the indentation of the return False statement and bring it outside the for loop. Then what you get is the boolean OR of all the keys, or False if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.

myDictionary={0:'零',":'空字符串',None:'无值',False:'布尔假值',():'空元组'}


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

1号路

len(given_dic_obj) 

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

2号路

bool(given_dic_object)

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