Use defaultdict() to handle missing keys in a dictionary

vijoin profile image Victor Inojosa ・1 min read

Sometimes you have a bunch of data into a dictionary and you don't know for sure if all the keys will be in there.

... and you'll be handling this with:

data_dict.get('key1', 'missing')
data_dict.get('key2', 'missing')
data_dict.get('key3', 'missing')
data_dict.get('key4', 'missing')

In the code above, if any of those keys does not exist in the dictionary it will return a missing string.

A better approach for this could be the use of collections.defaultdict()

from collections import defaultdict

data = {'name': 'Victor', 'lastname': 'Inojosa', 'year': 1985}

def _get_default_error():
    return "Oops! MISSING"

#data = (lambda: "MISSING", data)
data = defaultdict(_get_default_error, data)

if __name__ == "__main__":
    print(data['gender']) # Oops! MISSING
    print(data['city']) # Oops! MISSING

defaultdict requires a callable object (a method without invoke). As you can see you could also use an anonymous lambda function to return a simple string.

I hope this could help you in your projects! Bye!


Editor guide