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

新手上路,请多包涵

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

原文由 Unsparing 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 246
2 个回答

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

原文由 user2555451 发布,翻译遵循 CC BY-SA 3.0 许可协议

以下是检查字典是否为空的三种方法。我更喜欢只使用第一种方式。其他两种方式太罗嗦了。

 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"

原文由 doubleo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏