How To Use Default Dicts

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

Preliminaries

import collections

Create A DefaultDict

Default Dicts work just like regular dictionaries, except a key is called that doesn't have a value, a default value (note: value, not key) is supplied.

# Create a defaultdict with the default value of 0 (int's default value is 0)
arrests = collections.defaultdict(int)

Add A New Key With A Value

# Add an entry of a person with 10 arrests
arrests['Sarah Miller'] = 10
# View dictionary
arrests
defaultdict(int, {'Sarah Miller': 10})

Add A New Key Without A Value

# Add an entry of a person with no value for arrests,
# thus the default value is used
arrests['Bill James']
0
# View dictionary
arrests
defaultdict(int, {'Bill James': 0, 'Sarah Miller': 10})