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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23177439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:25:13  来源:igfitidea点击:

Python: Checking if a 'Dictionary' is empty doesn't seem to work

pythondictionary

提问by Unsparing

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

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

采纳答案by Unsparing

Empty dictionaries evaluate to Falsein Python:

空字典在 Python 中求值为False

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

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

因此,您的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()))

回答by doubleo

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.

您可以通过以下三种方法检查 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"

回答by chhotu sardar

use 'any'

使用“任何”

dict = {}

if any(dict) :

     # true
     # dictionary is not empty 

else :

     # false 
     # dictionary is empty

回答by wieczorek1990

Why not use equality test?

为什么不使用相等测试?

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

回答by Achilles Ram Nakirekanti

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

if length is zero means that dict is empty

如果长度为零意味着 dict 为空

回答by MortenB

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

您也可以使用 get()。最初我相信它只检查密钥是否存在。

>>> 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.

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

回答by Shagun Pruthi

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.

虽然方法 1 更严格,因为当 a = None 时,方法 1 会提供正确的结果,但方法 2 会给出不正确的结果。

回答by Della

A dictionary can be automatically cast to boolean which evaluates to Falsefor empty dictionary and Truefor non-empty dictionary.

字典可以自动转换为布尔值,其计算结果False为空字典和True非空字典。

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 {}.

如果这看起来太惯用了,您还可以测试len(myDictionary)零或set(myDictionary.keys())空集,或者简单地测试与{}.

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

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

  1. The return Falsestatement is indented one level too deep. It should be outside the for loop and at the same level as the forstatement. 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 Falsestatement and bring it outside the forloop. Then what you get is the boolean ORof all the keys, or Falseif the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.
  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'}

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