Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:Efficient way to check if dictionary is empty or not [duplicate]

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.

like image 532
username_4567 Avatar asked Nov 09 '12 16:11

username_4567


People also ask

How do you check if a dictionary is empty in Python?

# 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!

How do you check if a nested dictionary is empty in Python?

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.

Does an empty dictionary return false?

If the dictionary is empty, it returns None which is not == False .

Does copy () work on dictionaries in Python?

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.


2 Answers

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)

like image 143
Wajih Avatar answered Oct 06 '22 05:10

Wajih


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 
like image 44
noname Avatar answered Oct 06 '22 05:10

noname