Default dict keys to avoid KeyError Default dict keys to avoid KeyError python python

Default dict keys to avoid KeyError


You can use your_dict.get(key, "default value") instead of directly referencing a key.


Don't use the "default" argument name. For example, if we want 1.0 as default value,

rank = dict.get(key, 1.0)

For more details:TypeError: get() takes no keyword arguments


If you can't define a default value and want to do something else (or just omit the entry):

if key in dict:    rank = dict[key]else:    # do something or just skip the else block entirely