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?
Check if a Dictionary is Empty using len()
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.
Another way of creating an empty dictionary is to use the dict() function without passing any arguments.
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.
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.
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.
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