Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to check empty dictionary and empty values

I am using these kind of dictionaries, they can be or totally empty like collection_a or contain a single one level nested dictionary which might be empty. It wont have more levels.

collection_a = {}
collection_b = {"test": {}}

print is_empty(collection_a)
print is_empty(collection_b)

def is_empty(collection):
    return not all(collection.values())

or

def is_empty(collection):
    return not bool(collection.values())

Isnt there an unique way to check if a or b have values?

You can check all(collection_b.values()) but that wont work for collection_a where it will return True

You can also check bool(collection_a.values()) but that wont work for collection_b where it will return True...

Isnt there an unique way to include both cases?

like image 449
lapinkoira Avatar asked Oct 17 '17 14:10

lapinkoira


People also ask

How do I check if a dictionary is empty?

Check if a Dictionary is Empty using len()

Can a dictionary have empty values?

Python empty dictionary means that it does not contain any key-value pair elements. To create an empty dictionary in this example, we can use a dict(), which takes no arguments. If no arguments are provided, an empty dictionary is created.

How do you represent an empty dictionary in Python?

Another way of creating an empty dictionary is to use the dict() function without passing any arguments.

How do I check if a list is empty in Python?

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.


2 Answers

Test with any, since empty dicts are falsy:

>>> collection_a = {}
>>> collection_b = {"test": {}}
>>> any(collection_a.values())
False
>>> any(collection_b.values())
False

This assumes that the dictionary value is always a dictionary.

like image 140
Moses Koledoye Avatar answered Oct 27 '22 21:10

Moses Koledoye


If you want to check whether the dictionary has values, and whether all the values (if any) are "truthy", just combine your two tests:

bool(collection) and all(collection.values())

(The bool in the first part is optional, but without it you will get an unintuitive {} if the dictionary is empty.)

Of course, if you only want to check whether any of the values in the collection are "truthy" (this is not entirely clear from your question), all you have to do is any(collection), as already stated in other answers; this will at the same time also check whether the collection is non-empty.

like image 23
tobias_k Avatar answered Oct 27 '22 20:10

tobias_k