Python: How to use the dictionary get( ) method

Lets say we have a small Python dictionary called fruit that looks like this:

fruit = {'a':'apple', 'b':'banana', 'c':'cherry'}

The most common way to get a value is to retrieve it by its key, using this special syntax:

name_of_dictionary[ name_of_key ]

By using the name of the key in brackets after the name of the dictionary, we get the value associated with that key. Using this syntax assumes the presence of the key in the dictionary. If we are not sure that the key exists, then we would need to use a try / except block to mitigate the possibility that it doesn’t. For example, if we try to get the value associated with the key ‘d’:

fruit = {'a':'apple', 'b':'banana', 'c':'cherry'}

print fruit['d']

we get an error message:

KeyError: 'd'

This is mitigated by using a try / except block:

fruit = {'a':'apple', 'b':'banana', 'c':'cherry'}

try:
    print fruit['d']
except:
    print "Key 'd' doesn't exist in the dictionary, so adding it now.."
    fruit['d'] = 'dates

Not surprisingly, Python comes with an alternative method of getting a dictionary value where a key might not exist. This is accomplished with the dictionary get(key, default) function. This function allows you to attempt to get the value associated to a key that may or may not be present in the dictionary. The syntax uses a dot instead of square backets, and the default value is preset, so we don’t need to use a try / except block. For example:

value = name_of_dictionary.get(key, default_value)

The default_value prevents the need to use a try / except block because it determines what will be returned if the key is not present. For example, setting the default value to None:

fruit = {'a':'apple', 'b':'banana', 'c':'cherry'}

b = fruit.get('b', None)
d = fruit.get('d', None)

print "b:", b
print "d:", d

Yields:

b: banana
d: None

Leave a Reply