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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)