Default dict keys to avoid KeyError

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

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