Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

README.md

defaultdict

A dictionary subclass that returns a default value for missing keys instead of raising a KeyError. See associative array — Wikipedia.

Usage

from collections import defaultdict
d = defaultdict(factory)

The factory is any callable — list, int, lambda: None, etc. When a missing key is accessed, factory() is called to create the default value.

Common patterns

Factory Default value Useful for
list [] Grouping values by key
int 0 Counting occurrences
lambda: None None Optional lookups

Run

python defaultdict.py

Demonstrates missing key handling, grouping words by first letter, and counting word frequency.