Title: How To Use Default Dicts
Slug: how_to_use_default_dicts
Summary: How To Use Default Dicts in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Basics
Authors: Chris Albon
Interesting in learning more? Check out Fluent Python
In [1]:
import collections
In [2]:
# Create a defaultdict with the default value of 0 (int's default value is 0)
arrests = collections.defaultdict(int)
In [3]:
# Add an entry of a person with 10 arrests
arrests['Sarah Miller'] = 10
In [4]:
# View dictionary
arrests
Out[4]:
In [5]:
# Add an entry of a person with no value for arrests,
# thus the default value is used
arrests['Bill James']
Out[5]:
In [6]:
# View dictionary
arrests
Out[6]: