How to check if dictionary is empty or not? more specifically, my program starts with some key in dictionary and I have a loop which iterates till there are key in dictionary. Overall algo is like this:
Start with some key in dict
while there is key in dict
do some operation on first key in dict
remove first key
Please note that some operation
in above loop may add new keys to dictionary. I've tried for key,value in d.iteritems()
but it is failing as during while loop some new key are added.
# Checking if a dictionary is empty by checking its length empty_dict = {} if len(empty_dict) == 0: print('This dictionary is empty! ') else: print('This dictionary is not empty! ') # Returns: This dictionary is empty!
Example 2: Check if Dictionary is Empty using len() In the following program, we will use len() builtin function to check if the dictionary is empty or not. myDict = {} if (len(myDict) == 0): print('The dictionary is empty. ') else: print('The dictionary is not empty.
If the dictionary is empty, it returns None which is not == False .
Use copy()This is a built-in Python function that can be used to create a shallow copy of a dictionary. This function takes no arguments and returns a shallow copy of the dictionary. When a change is made to the shallow copy, the original dictionary will remain unchanged.
any(d)
This will return true if the dict. d contains at least one truelike key, false otherwise.
Example:
any({0:'test'}) == False
another (more general) way is to check the number of items:
len(d)
I just wanted to know if the dictionary i was going to try to pull data from had data in it in the first place, this seems to be simplest way.
d = {} bool(d) #should return False d = {'hello':'world'} bool(d) #should return True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With