get()
method to access values from a dictionary PYL-R1715In 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.
if key in my_mapping:
value = my_mapping[key]
else:
value = "Not Found"
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'