DefaultDict in Python

Level 4252 keystrokes

This uses defaultdict to automatically create default values for missing keys, useful for grouping data.

Python code

# Import defaultdict from collections
1from collections import defaultdict
2
# Missing keys automatically get an empty list
3groups = defaultdict(list)
# (category, item) pairs to group
4data = [("fruit", "apple"), ("veg", "carrot"), ("fruit", "banana")]
5
# Unpack each pair into category and item
6for category, item in data:
# No need to check if the key exists before append
7 groups[category].append(item)
8
# Loop over each key and its list (in insertion order)
9for key, values in groups.items():
# Prints fruit: ['apple', 'banana'] and veg: ['carrot']
10 print(f"{key}: {values}")

Output

fruit: ['apple', 'banana']
veg: ['carrot']
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.

  • "× 14
  • ,× 7
  • (× 7
  • )× 7
  • :× 3
  • .× 2
  • [× 2
  • ]× 2
  • {× 2
  • }× 2

More Python examples at level 4

← Python typing practice