Python: Checking if a 'Dictionary' is empty doesn't seem to work
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:34 Accepted answer (Score 1090)
01:05 Answer 2 (Score 201)
01:27 Answer 3 (Score 29)
01:41 Answer 4 (Score 21)
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/2317...
Accepted answer links:
[evaluate to ]: https://docs.python.org/2/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:34 Accepted answer (Score 1090)
01:05 Answer 2 (Score 201)
01:27 Answer 3 (Score 29)
01:41 Answer 4 (Score 21)
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/2317...
Accepted answer links:
[evaluate to ]: https://docs.python.org/2/library/stdtyp...
--
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 = {}
-
if a == {}: print ('empty dict') -
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.