Python safe dictionary key access

Question:

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 ifs or custom functions?

I believe there should be, because this is a very common usage.

Asked By: nipunasudha

||

Answers:

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 = data.get('color', 'red')
Answered By: Martijn Pieters

Check out dict.get(). You can supply a value to return if the key is not found in the dictionary, otherwise it will return None.

>>> data = {'color': 'yellow'}
>>> data.get('color')
'yellow'
>>> data.get('name') is None
True
>>> data.get('name', 'nothing')
'nothing'
Answered By: mhawke