Skip to content

[New Rule] dict use get with default rather than if in mydict: else #72

@jcpunk

Description

@jcpunk

Explanation

Dictionaries have built in methods for "fetch this value if it exists or use this default". The pattern of checking for the key and then assigning tends to pop up here and there. It is a good practice to validate the data exists before accessing it, but in this case it is more complex than just using the language buit-in behavior.

Example

# Bad
if "my_key" in example_dict:
    thing = example_dict["my_key"]
else:
    thing = "default_value"

# Good
thing = example_dict.get("my_key", "default_value")

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions