Code

Count & Group

Two tools from collections make aggregation painless.

Counter

A Counter is a dict that counts things:

from collections import Counter

c = Counter(["oil", "wick", "oil", "lens", "oil"])
c["oil"]            # 3
c["dragon"]         # 0  (missing keys count as 0)
c.most_common(2)    # [('oil', 3), ('wick', 1)]
c.update(["wick"])  # add more counts

defaultdict

A defaultdict creates a starting value the first time you touch a missing key, so you never need if key not in d:.

from collections import defaultdict

fuel = defaultdict(int)       # missing -> 0
for isle, litres in [("Ember", 5), ("Frost", 2), ("Ember", 3)]:
    fuel[isle] += litres
dict(fuel)                    # {'Ember': 8, 'Frost': 2}

groups = defaultdict(list)    # missing -> []
groups["Ember"].append("Ada")

Assignment

  1. top_items(sales, n): sales is a list of item names. Return the n most common as a list of (name, count) tuples, most common first.
  2. fuel_by_island(records): records is a list of (island, litres) tuples. Return a dict of island to total litres.
  3. crew_by_role(crew): crew is a list of (name, role) tuples. Return a dict of role to alphabetically sorted list of names.