Python dict get method

The Python dictionary provides an associate array interface to get the value associated with a key:

>>> d = { 1:"cat", 2:"rat" }
>>> d[1]
'cat'

However, this interface is not very friendly if you lookup a key that does not exist. In such a case, it throws a KeyError exception:

>>> d[3]
KeyError: 3

Python dictionary provides a get method that is safer, it returns a None value if the key is not present:

>>> print(d.get(3))
None

This method is actually cooler than it looks cause you can make it return any default value you want when the key is not present in the dictionary. You do this by passing the default value as the second argument:

>>> print(d.get(1, "elephant"))
cat
>>> print(d.get(3, "elephant"))
elephant

Bonus trick

In many cases, we might have the key in the dictionary, but its value is set to some default value like None or empty string or empty list or empty dict or such values. But at the point we are picking values from keys assume we want such default-valued keys to return a different default value. The trick is that since such default values default to False in Python, we can use that to our advantage.

For example, say the dictionary is already created and not under our control. But, whenever I read values from it, I want elephant if the key does not exist or if the value is a default value that evaluates to False. It gives rise to an elegant Python idiom using get method and or operator:

>>> d = { 1:"cat", 2:"rat", 3:None, 4:"" }
>>> v = d.get(1) or "elephant" ; print(v)
cat
>>> v = d.get(3) or "elephant" ; print(v)
elephant
>>> v = d.get(4) or "elephant" ; print(v)
elephant
>>> v = d.get(99) or "elephant" ; print(v)
elephant
Advertisements

2 thoughts on “Python dict get method”

  1. dict.get can also take a second argument, which is the default value, which defaults to None. So you could just use d.get(99, “elephant”). Note: this has slightly different behavior in case you have a ‘falsy’ value in your dict, e.g.

    d = { 1:””, 2: 0, 3: None, 4: False }
    print(d.get(2) or “elephant”) // “elephant”
    print(d.get(2, “elephant”) // 0

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s