What’s the most succinct way of saying, in Python, “Give me dict['foo'] if it exists, and if not, give me this other value bar“? If I were using an object rather than a dictionary, I’d use getattr:
getattr(obj, 'foo', bar)
but this raises a key error if I try using a dictionary instead (a distinction I find unfortunate coming from JavaScript/CoffeeScript). Likewise, in JavaScript/CoffeeScript I’d just write
dict['foo'] || bar
but, again, this yields a KeyError. What to do? Something succinct, please!
dict.get(key, default)returnsdict[key]if key in dict, else returns default.Note that the default for
defaultisNoneso if you saydict.get(key)and key is not in dict then this will just returnNonerather than raising aKeyErroras happens when you use the[]key access notation.