A Beginner’s Guide to Python Defaultdict – Python Tutorial

By | September 16, 2019

Python dict data type does not provide default value, which means we can not read a nonexistent key. In this tutorial, we will discuss python defaultdict, it supplies a default value for dict data type.

Python dict data type

Create a dict

member =  {'age':23, 'name': 'John'}
print(member)

The memeber is:

{'name': 'John', 'age': 23}

Read value with nonexistent key

sex  = member['sex']
print(sex)

You will get this error.

KeyError: ‘sex’

Create a python dict with default value

Import library

from collections import defaultdict

Set default value for python dict

member = defaultdict(lambda: 'male')

Add key: value for dict

member['age'] = 23
member['name'] = 'John'

Read value with key

name  = member['name']
print(name)

The name is John

Read value with nonexistent key

sex  = member['sex']
print(sex)

This code will return default value: male

Leave a Reply

Your email address will not be published. Required fields are marked *