coding style - The most Pythonic way of checking if a value in a dictionary is defined/has zero length -
say have dictionary, , want check if key mapped nonempty value. 1 way of doing len function:
mydict = {"key" : "value", "emptykey" : ""} print "true" if len(mydict["key"]) > 0 else "false" # prints true print "true" if len(mydict["emptykey"]) > 0 else "false" # prints false
however, 1 can rely on semantics of python , how if object defined evaluates true , leave out len call:
mydict = {"key" : "value", "emptykey" : ""} print "true" if mydict["key"] else "false" # prints true print "true" if mydict["emptykey"] else "false" # prints false
however, i'm not sure more pythonic. first feels "explicit better implicit", second feels "simple better complex".
i wonder if leaving out len call bite me dict i'm working doesn't contain strings, contain other len-able types (lists, sets, etc). otoh, in former (with len call) if none gets stored value code blow up, whereas non-len version work expected (will eval false).
which version safer , more pythonic?
edit: clarifying assumptions: know key in dictionary, , know values len-able. cannot avoid having zero-length values enter dictionary.
edit #2: seems people missing point of question. i'm not trying determine pythonic/safest way of checking if key present in dictionary, i'm trying check if a value has 0 length or not
if know key in dictionary, use
if mydict["key"]: ...
it simple, easy read, , says, "if value tied 'key' evaluates true
, something". important tidbit know container types (dict, list, tuple, str, etc) evaluate true
if len
greater 0.
it raise keyerror
if premise key in mydict
violated.
all makes pythonic.
Comments
Post a Comment