typestar

Group items by key in Python

SQL's GROUP BY, in three lines of Python.

from collections import defaultdict

def group_by(items, key):
    groups = defaultdict(list)
    for item in items:
        groups[key(item)].append(item)
    return dict(groups)

How it works

  1. defaultdict(list) creates a bucket the first time a key appears.
  2. Each item lands in the bucket its key function picks.
  3. Returns the groups as a plain dict.

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
159
Tokens
40
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 24 seconds.

Type this snippet

Step 10 of 10 in Collections, step 32 of 72 in Language basics.

← Previous Next →