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

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


Empty dictionaries evaluate to False in Python:

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

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"


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

if length is zero means that dict is empty


matomo