Python: Checking if a Dictionary is empty doesnt seem to work

Python: Checking if a Dictionary is empty doesnt seem to work

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

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

Python: Checking if a Dictionary is empty doesnt seem to work

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

if length is zero means that dict is empty

Leave a Reply

Your email address will not be published. Required fields are marked *