I am looking for a convenient, safe python dictionary key access approach. Here are 3 ways came to my mind.
data = {'color': 'yellow'}
# approach one
color_1 = None
if 'color' in data:
color_1 = data['color']
# approach two
color_2 = data['color'] if 'color' in data else None
# approach three
def safe(obj, key):
if key in obj:
return obj[key]
else:
return None
color_3 = safe(data, 'color')
#output
print("{},{},{}".format(color_1, color_2, color_3))
All three methods work, of-course. But is there any simple out of the box way to achieve this without having to use excess if
s or custom functions?
I believe there should be, because this is a very common usage.
You missed the canonical method, dict.get()
:
color_1 = data.get('color')
It'll return None
if the key is missing. You can set a different default as a second argument:
color_2 = dict.get('color', 'red')