How to Remove Empty Dictionaries from a List of Dictionaries in Python?

Estimated read time 1 min read

You can remove empty dictionaries from a list of dictionaries using a list comprehension with a filter condition that checks if the dictionary is empty or not. Here’s an example:

list_of_dicts = [{}, {'a': 1}, {}, {'b': 2}, {}, {'c': 3}]
new_list_of_dicts = [d for d in list_of_dicts if d]
print(new_list_of_dicts) # Output: [{'a': 1}, {'b': 2}, {'c': 3}]

In this example, we have a list of dictionaries (list_of_dicts). We want to create a new list (new_list_of_dicts) that only contains dictionaries that are not empty. We achieve this by using list comprehension with a filter condition if d, which checks if the dictionary d is not empty. The resulting list contains only the dictionaries with key-value pairs in them.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply