2 ms·
If you don't care about a key existing, then this works. do_something(dict_.get("key", None)) I use that a lot for data parsing. Passing the exception is
by mywittyname 5y ago
If you don't care about a key existing, then this works.
do_something(dict_.get("key", None))
I use that a lot for data parsing. Passing the exception is not very clean IMHO. I stick to d[key] nomenclature when I need assurance that all the keys are present in the dictionary, and .get(key,None) when I don't.
- stevesimmons 5y ago.get("key") is enough, as the default is already None. And if you care about the default value being a particular type, when there may also be None in the input stream, do something like: x.get("key") or [] or str(x.get("key") or "") # Guarantee strings and avoid "None"!