The most Pythonic way of checking if a value in a dictionary is defined/has zero length

If you know the key is in the dictionary, use

if mydict["key"]:
    ...

It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True if their len is greater than 0.

It will also raise a KeyError if your premise that a key is in mydict is violated.

All this makes it Pythonic.


print (bool(mydict.get('key')))

or, in an if statement:

print ('True' if mydict.get('key') else 'False')

If you the value not being present is an error case (i.e. you expect it to be there), you should choose solution #2, i.e.

print ('True' if mydict['key'] else 'False')

That allows mydict['key'] to choose the most efficient definition for being empty. For some objects (such as ones in clusters), determining the actual length is a fairly complicated operation, whereas it's simple to determine whether the object is empty or not.

You could also compare to '', i.e. mydict['key'] == '', to make your expression abundantly clear. Using len works, but is not as intuitive.

In summary, leave it to the tested object to define whether it's empty or not and just cast it to bool.


I'd use a variation of the first option:

>>> mydict = {"key" : "value", "emptykey" : ""}
>>> print bool(mydict["key"])
True
>>> print bool(mydict["emptykey"])
False

Any class that provides __len__ can be converted into a boolean directly (see Truth Value Testing), so bool(container) is the equivalent of bool(len(container)). A length of 0 will become the boolean False while all other lengths will be True. You'll never have a negative length object. Also, the booleans True and False can be printed directly via print, so you don't need the conditional.