top of page

Python: Dictionary Lookup With a Default Value

Updated: Jun 11, 2018


How do you lookup keys in the python dictionary? You will typically find or write a code like this (ignore initialization part of dictionary for the sake of example, it will typically be done in another part of the program):


config = {}

config["retry"] = 3

config["timeout"] = 60


def LookupConfig(key):

if key in config:

return config[key]

else:

return None # May also throw an exception here


key = "retry"

print(key,"has value: ", LookupConfig(key))


Result:

retry has value: 3


This is fine. But did you notice we added “key in map” check before accessing the key. If we forgot that or remove that, we will get a KeyError exception, which would need to be handled. Some version of above code would go for default value by catching that exception. That works, too.


But is there a better pythonic way to do this lookup, especially given the fact dictionary lookup is such a basic task in python? As you guessed correctly, there is a better way and that is ‘get’ method of dictionary container. Here’s how above code can be re-written with that ‘get’ method employed:


config = {}

config["retry"] = 3

config["timeout"] = 60


def LookupConfigv2(key):

return config.get(key, None) # None is just an example, but default value can be anything


key = "retry"

print(key,"has value: ", LookupConfigv2(key))


key = "Retry" # Typo, oops!

print(key,"has value: ", LookupConfigv2(key))


Result:

retry has value: 3

Retry has value: None


Summary:

get’ method of dictionary type checks if the key is present and if yes, returns the value else returns the default value we specify. This is pretty simple but same time quite a powerful technique to employ in lookups. It not only reduces code around lookups, it also self-documents employed default values and makes code more explicit.

67 views0 comments
bottom of page