问题:Python:检查“字典”是否为空似乎不起作用

我正在尝试检查字典是否为空,但是行为不正常。它只是跳过它并显示“ 联机”,除了显示消息外没有任何其他内容。有什么主意吗?

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

I am trying to check if a dictionary is empty but it doesn’t behave properly. It just skips it and displays ONLINE without anything except of display the message. Any ideas why ?

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

回答 0

空字典在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()))

Empty dictionaries evaluate to False in Python:

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

Thus, your isEmpty function is unnecessary. All you need to do is:

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

回答 1

您可以通过以下三种方法检查dict是否为空。我更喜欢只使用第一种方法。其他两种方式过于罗y。

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"

Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.

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"

回答 2

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

如果length为零,则表示dict为空

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

if length is zero means that dict is empty


回答 3

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

        a= {}

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

尽管方法1st在a = None时更为严格,但方法1将提供正确的结果,而方法2将提供不正确的结果。

Simple ways to check an empty dict are below:

        a= {}

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

Although method 1st is more strict as when a = None, method 1 will provide correct result but method 2 will give an incorrect result.


回答 4

字典可以自动转换为布尔值,布尔值为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循环。然后,您得到的是所有键的布尔值OR,或者False如果字典为空。仍然会有误报和误报。进行更正并针对以下词典进行测试以获取证据。

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

A dictionary can be automatically cast to boolean which evaluates to False for empty dictionary and True for non-empty dictionary.

if myDictionary: non_empty_clause()
else: empty_clause()

If this looks too idiomatic, you can also test len(myDictionary) for zero, or set(myDictionary.keys()) for an empty set, or simply test for equality with {}.

The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.

  1. 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.
  2. 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.
  3. 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:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}


回答 5

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

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

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

You can also use get(). Initially I believed it to only check if key existed.

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

What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.


回答 6

为什么不使用平等测试?

def is_empty(my_dict):
    """
    Print true if given dictionary is empty
    """
    if my_dict == {}:
        print("Dict is empty !")

Why not use equality test?

def is_empty(my_dict):
    """
    Print true if given dictionary is empty
    """
    if my_dict == {}:
        print("Dict is empty !")

回答 7

使用“任何”

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

use ‘any’

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。