How to check if a dictionary is empty?
Question:
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()))
Answers:
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"
use ‘any’
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
d = {}
print(len(d.keys()))
If the length is zero, it means that the dict is empty.
You can also use get(). Initially I believed it to only check if key existed.
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.
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.
A dictionary can be automatically cast to boolean which evaluates to False
for empty dictionary and True
for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary)
for zero, or set(myDictionary.keys())
for an empty set, or simply test for equality with {}
.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
- The
return False
statement is indented one level too deep. It should be outside the for loop and at the same level as the for
statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None
, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives.
- If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
- Let us say you correct the indentation of the
return False
statement and bring it outside the for
loop. Then what you get is the boolean OR of all the keys, or False
if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.
myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
test_dict = {}
if not test_dict.keys():
print "Dict is Empty"
1st Way
len(given_dic_obj)
It returns 0 if there are no elements.
Else, returns the size of the dictionary.
2nd Way
bool(given_dic_object)
Returns False
if the dictionary is empty, else return True.
I use:
if len(dict)>0:
# True
else:
# False
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()))
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"
use ‘any’
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
d = {}
print(len(d.keys()))
If the length is zero, it means that the dict is empty.
You can also use get(). Initially I believed it to only check if key existed.
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.
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.
A dictionary can be automatically cast to boolean which evaluates to False
for empty dictionary and True
for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary)
for zero, or set(myDictionary.keys())
for an empty set, or simply test for equality with {}
.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
- The
return False
statement is indented one level too deep. It should be outside the for loop and at the same level as thefor
statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will returnNone
, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives. - If the dictionary is not empty, then the code will process only one key and return its value cast to boolean. You cannot even assume that the same key is evaluated each time you call it. So there will be false positives.
- Let us say you correct the indentation of the
return False
statement and bring it outside thefor
loop. Then what you get is the boolean OR of all the keys, orFalse
if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.
myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
test_dict = {}
if not test_dict.keys():
print "Dict is Empty"
1st Way
len(given_dic_obj)
It returns 0 if there are no elements.
Else, returns the size of the dictionary.
2nd Way
bool(given_dic_object)
Returns False
if the dictionary is empty, else return True.
I use:
if len(dict)>0:
# True
else:
# False