Python dict.get('key') versus dict['key']

foundling picture foundling · May 21, 2015 · Viewed 15.2k times · Source

Why does this throw a KeyError:

d = dict()
d['xyz']

But this does not?

d = dict()
d.get('xyz')

I'm also curious if descriptors play a role here.

Answer

Martin Konecny picture Martin Konecny · May 21, 2015

This is simply how the get() method is defined.

From the Python docs:

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

The default "not-found" return value is None. You can return any other default value.

d = dict()
d.get('xyz', 42)  # returns 42