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]

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))

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"))
>>> print(d.get(3, "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)
>>> v = d.get(3) or "elephant" ; print(v)
>>> v = d.get(4) or "elephant" ; print(v)
>>> v = d.get(99) or "elephant" ; print(v)

How to convert Python dict to class object with fields

A Python dict is extremely versatile. However, there might be situations where you want to access the dict as if it were a class object and the keys were its fields. This can be easily done by using a namedtuple. Just give it a name and the use the keys to populate its named fields. Set the values for those fields by passing the values from the dict. It all boils down to a single line.

This example code demonstrates the above: