DefaultDict Usage in Python

Level 4179 keystrokes

This uses defaultdict to automatically create default values. Missing keys get initialized with the factory function (list).

Python code

# Import defaultdict from collections module
1from collections import defaultdict
2
# Create defaultdict with list as default factory
3groups = defaultdict(list)
# Sample data as list of tuples (key, value)
4data = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
5
# Iterate through key-value pairs
6for key, val in data:
# Automatically creates empty list if key doesn't exist
7 groups[key].append(val)
8
# Convert to regular dict and print
9print(dict(groups))

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.

  • ,× 8
  • "× 8
  • (× 8
  • )× 8
  • [× 2
  • ]× 2
  • =× 2
  • :× 1
  • .× 1

More Python examples at level 4

← Python typing practice