The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Python: Checking If A 'Dictionary' Is Empty Doesn'T Seem To Work
00:29 Accepted Answer Score 1221
00:51 Answer 2 Score 238
01:10 Answer 3 Score 35
01:19 Answer 4 Score 33
01:37 Thank you

--

Full question
https://stackoverflow.com/questions/2317...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 1221


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



ANSWER 2

Score 238


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"



ANSWER 3

Score 35


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

If the length is zero, it means that the dict is empty.




ANSWER 4

Score 33


Simple ways to check an empty dict are below:

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

Method 1 is more strict, because when a = None, method 1 will provide the correct result, but method 2 will give an incorrect result.