Defaultdict Usage in Python

Level 5216 keystrokes

This uses defaultdict to group values by key without KeyError checks. defaultdict automatically creates default values for missing keys.

Python code

# Import defaultdict from collections module
1from collections import defaultdict
2
# Create a defaultdict where missing keys get empty list []
3groups = defaultdict(list)
# Sample data: tuples of (key, value)
4data = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
5
# Group values by key - no need to check if key exists
6for key, val in data:
# If key doesn't exist, defaultdict creates empty list first
7 groups[key].append(val)
8
# Print each group
9for key, vals in groups.items():
10 print(f"{key}: {vals}")

Output

a: [1, 3]
b: [2, 4]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 10
  • ,× 9
  • (× 8
  • )× 8
  • :× 3
  • .× 2
  • [× 2
  • ]× 2
  • {× 2
  • }× 2

More Python examples at level 5

← Python typing practice