snippetpythonCritical
How to check if a dictionary is empty?
Viewed 0 times
emptycheckhowdictionary
Problem
I am trying to check if a dictionary is empty but it doesn't behave properly. It just skips it and displays ONLINE without anything aside from the display the message. Any ideas why ?
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()))Solution
Empty dictionaries evaluate to
Thus, your
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()))Code Snippets
>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>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()))Context
Stack Overflow Q#23177439, score: 1276
Revisions (0)
No revisions yet.