Python:检查'Dictionary'是否为空似乎不起作用

Uns*_*ing 337 python dictionary

我正在尝试检查字典是否为空但它的行为不正常.除了显示消息之外,它只是跳过它并显示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())) 
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 644

空字典在Python中评估False:

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>
Run Code Online (Sandbox Code Playgroud)

因此,您的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()))
Run Code Online (Sandbox Code Playgroud)

  • @Wajih你链接是无关紧要的:`bool({False:False})`仍然评估为'True`.你给出的链接对应于`any`method,它取决于键. (7认同)
  • 我觉得“不是字典”不是明确的 (4认同)
  • 同意,我觉得使用布尔值和 `not <dict>` 也不太清楚 (2认同)

dou*_*leo 107

以下三种方法可以检查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"
Run Code Online (Sandbox Code Playgroud)

  • 叹息......每个人都喜欢成为"pythonic",并且最不喜欢打字.首先,另一个标准是可读性.其次,上面答案中的第一个测试不仅在dict存在且为空时,而且如果test_dict为None也是如此.因此,只有当您知道dict对象存在时(或差异无关紧要时)才使用此测试.第二种方式也有这种行为.如果test_dict为None,则只有第三种方式吠叫. (26认同)
  • 由于我也有同样的担忧,尽管技术上是正确的,但不赞成这一点。@AndreasMaier (3认同)

Sha*_*thi 15

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

        a= {}

    1. if a == {}:
           print ('empty dict')
    2. if not a:
           print ('empty dict')
Run Code Online (Sandbox Code Playgroud)

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


小智 12

dict = {}
print(len(dict.keys()))
Run Code Online (Sandbox Code Playgroud)

如果length为零则表示dict为空

  • 虽然此代码段可以解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量.请记住,您将来会回答读者的问题,而这些人可能不知道您的代码建议的原因. (2认同)
  • `len(dict.keys())` 等价于 `len(dict)` (2认同)

Del*_*lla 9

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

if myDictionary: non_empty_clause()
else: empty_clause()
Run Code Online (Sandbox Code Playgroud)

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

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

  1. return False声明缩进一级太深。它应该在 for 循环之外并且与语句处于同一级别for。因此,如果存在某个键,您的代码将仅处理一个任意选择的键。如果键不存在,该函数将返回None,并将其转换为布尔值 False。哎哟! 所有空字典将被归类为假否定。
  2. 如果字典不为空,则代码将仅处理一个键并将其值转换为布尔值。您甚至不能假设每次调用时都会评估相同的键。所以会有误报。
  3. 假设您更正了return False语句的缩进并将其移出循环for。然后你得到的是所有键的布尔False,或者字典是否为空。但仍然会出现误报和误报。根据以下词典进行更正和测试以获取证据。

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


Arp*_*ini 5

第一种方式

len(given_dic_obj) 
Run Code Online (Sandbox Code Playgroud)

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

第二种方式

bool(given_dic_object)
Run Code Online (Sandbox Code Playgroud)

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