The Python Oracle

Pythonic way to check empty dictionary and empty values

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cool Puzzler LoFi

--

Chapters
00:00 Pythonic Way To Check Empty Dictionary And Empty Values
00:48 Accepted Answer Score 12
01:03 Answer 2 Score 6
01:38 Answer 3 Score 1
01:54 Answer 4 Score 3
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/4679...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ACCEPTED ANSWER

Score 12


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.




ANSWER 2

Score 6


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.




ANSWER 3

Score 3


Because :

>>> dict={}
>>> not dict
True

So You can check like this :

collection_a = {"hello":1,"bye":2}
if collection_a:
    #do your stuff
    print("not empty")

collection_a = {}
if collection_a:
    print("dict is not empty")

if you want to check dict a or dict b then :

if collection_a or collection_b:
    print("not empty")



ANSWER 4

Score 1


Alternatively, bool() in combination with more-itertools' collapse():

import more_itertools

def has_value(thing):
    return bool(*more_itertools.collapse(thing))

>>> has_value({})
False
>>> has_value({''})
False
>>> has_value({0:['']})
False
>>> has_value({'test':[]})
True