首页 文章

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

提问于
浏览
231

我试图检查一个字典是否为空但它行为不正常 . 它只是跳过它并显示 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()))

8 回答

  • 8

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

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

    我喜欢得到的是它不会触发异常,因此它可以很容易地遍历大型结构 .

  • -6

    Python 3:

    def is_empty(dict):
       if not bool(dict):
          return True
       return False
    
    test_dict = {}
    if is_empty(test_dict):
        print("1")
    
    test_dict = {"a":123}
    if not is_empty(test_dict):
        print("1")
    
  • 469

    以下三种方法可以检查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"
    
  • 0
    dict = {}
    print(len(dict.keys()))
    

    如果length为零则表示dict为空

  • 81

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

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

    虽然方法1st比a = None时更严格,但方法1将提供正确的结果,但方法2将给出不正确的结果 .

  • -1

    使用'任何'

    dict = {}
    
    if any(dict) :
    
         # true
         # dictionary is not empty 
    
    else :
    
         # false 
         # dictionary is empty
    
  • 0

    Python中的空字典evaluate to 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()))
    
  • -3

    为什么不使用平等测试?

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

相关问题