Python

Python

Made by DeepSource

Use get() method to access values from a dictionary PYL-R1715

Anti-pattern
Major
Autofix

In case of checking if key exists in the dictionary and then fetching the value, it is recommended to use the built-in method dict.get(key[, default]). A pattern where you first ensure if a key exist in a dictionary and then get the value requires the dictionary lookup twice, which can be avoided by using get. get() returns the respective value if key exists in the dictionary, else returns a default value, avoiding the dictionary lookup twice.

Bad practice

if key in my_mapping:
    value = my_mapping[key]
else:
    value = "Not Found"

Recommended

value = my_mapping.get(key, "Not Found")

Note: DeepSource has stopped raising this issue when multiple keys are checked to set the value. Using get here would make code hard to read.**

dictionary = {}
if 'key1' in dictionary: 
    variable = dictionary['key1']
elif 'key2' in dictionary:  # Issue not raised
    variable = dictionary['key2']
else:
    variable = 'default'