w3resource

Python: Check whether all dictionaries in a list are empty or not


Check If All Dictionaries Are Empty

Write a Python program to check whether all dictionaries in a list are empty or not.

Visual Presentation:

Python List: Check whether all dictionaries in a list are empty or not.
Python List: Check whether all dictionaries in a list are full or not.

Sample Solution:

Python Code:

# Define a list 'my_list' containing three empty dictionaries
my_list = [{}, {}, {}]

# Define another list 'my_list1' containing dictionaries, one of which has a key-value pair
my_list1 = [{1: 2}, {}, {}]

# Check if all dictionaries in 'my_list' are empty (i.e., contain no key-value pairs)
# The 'not d for d in my_list' generator expression returns 'True' for each empty dictionary, and 'all' checks if they are all 'True'
print(all(not d for d in my_list))

# Check if all dictionaries in 'my_list1' are empty (i.e., contain no key-value pairs)
# The 'not d for d in my_list1' generator expression returns 'True' for the dictionaries that are empty, and 'all' checks if they are all 'True'
print(all(not d for d in my_list1)) 

Sample Output:

True                                                                                                          
False  

Flowchart:

Flowchart: Check whether all dictionaries in a list are empty or not

Python Code Editor:

Previous: Write a Python program to find the items starts with specific character from a given list.
Next: Write a Python program to flatten a given nested list structure.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.