Solved KeyError when reading a key that may not exist ELElaKowalskaOP 15 Oct, 08:22 My config dict sometimes lacks "timeout" and config["timeout"] crashes.
AMAmeliaRuns15 Oct, 13:36 Solutionreplies: 1Use .get() with a default:timeout = config.get("timeout", 30)It returns the default instead of raising KeyError.
OLOllieGrant15 Oct, 15:40replies: 1Or check first: if "timeout" in config:. .get() is usually shorter.
NONoahLoops15 Oct, 18:52Careful when 0 or "" is a valid value and you write config.get("timeout") or 30 — that replaces 0 with 30. .get("timeout", 30) doesn't have that problem.
Comments 5
Join the discussion CommentAlready have an account? Log in
Use
.get()with a default:It returns the default instead of raising KeyError.
Perfect, thanks.
Or check first:
if "timeout" in config:..get()is usually shorter.Good catch, I had exactly that with a retry count of 0.
Careful when 0 or "" is a valid value and you write
config.get("timeout") or 30— that replaces 0 with 30..get("timeout", 30)doesn't have that problem.