42

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.

nipunasudha
  • 2,427
  • 2
  • 21
  • 46

2 Answers2

93

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')
Martin Jambon
  • 4,629
  • 2
  • 22
  • 28
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
14

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'
mhawke
  • 84,695
  • 9
  • 117
  • 138