Code

Tally the Sightings

The collections module has upgraded containers for everyday jobs.

Counter counts things

from collections import Counter

seen = Counter(["gull", "whale", "gull", "otter", "gull"])
print(seen["gull"])          # 3
print(seen["kraken"])        # 0  (no KeyError!)
print(seen.most_common(2))   # [('gull', 3), ('whale', 1)]

defaultdict creates missing values for you

from collections import defaultdict

cargo = defaultdict(list)    # missing keys start as []
cargo["Amber Isle"].append("oil")
cargo["Amber Isle"].append("rope")
print(dict(cargo))           # {'Amber Isle': ['oil', 'rope']}

No more if key not in d: d[key] = []. Use defaultdict(int) for counters starting at 0, or defaultdict(set) for unique groups.

Assignment

  1. top_islands(visits, n): visits is a list of island names. Return the n most visited as a list of (island, count) tuples, most visited first.
  2. group_by_island(records): records is a list of (island, item) tuples. Return a dict mapping each island to a list of its items, in their original order.