dict, defaultdict and Counter
Most Python live-coding tasks start the same way: a list of rows, and a total, a count or the latest value per key. Revenue per customer, events per subscription, units in stock per item. A dict finds a key in O(1) on average, so one pass over the input is enough. Without it, the code grows a nested loop, loses the keys with zero or picks the wrong row when the input is out of order.
Three ways to read a key
Section titled “Three ways to read a key”from decimal import Decimal
prices = {"prd_03.monthly": Decimal("4.99"), "prd_03.annual": Decimal("79.99")}
print(prices["prd_03.monthly"]) # 4.99print(prices.get("prd_03.weekly")) # Noneprint(prices.get("prd_03.weekly", Decimal("0"))) # 0print("prd_03.weekly" in prices) # Falseprint(prices["prd_03.weekly"]) # KeyError: 'prd_03.weekly'| Expression | Key exists | Key is missing |
|---|---|---|
d[k] | the value | KeyError |
d.get(k) | the value | None |
d.get(k, default) | the value | default |
k in d | True | False |
Use d[k] when a missing key is a bug and the code should fail loudly. Use .get() or in when a missing key is a normal case. All four are O(1) on average, because a dict is a hash table.
Group and sum with defaultdict
Section titled “Group and sum with defaultdict”A plain dict needs a check before every update: if channel not in totals: totals[channel] = Decimal("0"). A defaultdict does this for you. For a new key it calls its factory: Decimal() returns Decimal('0'), int() returns 0, list() returns [].
from collections import defaultdictfrom decimal import Decimal
sales = [ ("north_market", Decimal("7.99")), ("south_market", Decimal("49.99")), ("north_market", Decimal("7.99")), ("web", Decimal("2.99")),]
totals = defaultdict(Decimal) # a new key starts at Decimal('0')for channel, amount in sales: totals[channel] += amount
print(dict(totals))# {'north_market': Decimal('15.98'), 'south_market': Decimal('49.99'), 'web': Decimal('2.99')}Money stays in Decimal from the first row to the result. The reasons are on Money and Decimal.
Reading a missing key adds it
Section titled “Reading a missing key adds it”A defaultdict creates the key on every read with [], not only on +=:
totals = defaultdict(Decimal)totals["north_market"] += Decimal("7.99")
print(totals["promo"]) # 0 -- reading a missing key...print(dict(totals)) # {'north_market': Decimal('7.99'), 'promo': Decimal('0')}A report that should list one channel now lists two. So return dict(totals): the caller gets a normal dict, and a wrong key gives KeyError instead of a silent zero. Inside your own code, check with k in totals or totals.get(k): neither of them adds the key.
A list per key, and the order of keys
Section titled “A list per key, and the order of keys”defaultdict(list) collects the rows of each key:
by_product = defaultdict(list)for product_id, tx_id in [("prd_03", "t1"), ("prd_09", "t2"), ("prd_03", "t3")]: by_product[product_id].append(tx_id)print(dict(by_product)) # {'prd_03': ['t1', 't3'], 'prd_09': ['t2']}A dict keeps its keys in insertion order. When the result must be sorted, sort the items before you build it:
from datetime import datetime
rows = [(datetime(2026, 9, 2), Decimal("9.99")), (datetime(2026, 8, 31, 23, 59), Decimal("4.99"))]
totals = defaultdict(Decimal)for start, amount in rows: totals[start.strftime("%Y-%m")] += amount
print(dict(totals)) # {'2026-09': Decimal('9.99'), '2026-08': Decimal('4.99')}print(dict(sorted(totals.items()))) # {'2026-08': Decimal('4.99'), '2026-09': Decimal('9.99')}Two levels of grouping
Section titled “Two levels of grouping”events = [("prd_03", "2026-09-01"), ("prd_03", "2026-09-01"), ("prd_09", "2026-09-01"), ("prd_03", "2026-09-02")]
per_day = defaultdict(lambda: defaultdict(int)) # product_id -> day -> countfor product_id, day in events: per_day[product_id][day] += 1print({product_id: dict(days) for product_id, days in per_day.items()})# {'prd_03': {'2026-09-01': 2, '2026-09-02': 1}, 'prd_09': {'2026-09-01': 1}}
flat = defaultdict(int) # the same with a tuple keyfor product_id, day in events: flat[(product_id, day)] += 1print(dict(flat))# {('prd_03', '2026-09-01'): 2, ('prd_09', '2026-09-01'): 1, ('prd_03', '2026-09-02'): 1}The argument of defaultdict must be a function that makes the default value. defaultdict(defaultdict(int)) passes a dict instead and fails with TypeError: first argument must be callable or None. lambda: defaultdict(int) is a function, so each new product gets its own inner dict.
A tuple key is often simpler: one level, and sorted(flat.items()) orders the rows by product, then by day.
Counter and equal counts
Section titled “Counter and equal counts”from collections import Counter
c = Counter(["south_market", "web", "north_market", "web", "north_market", "south_market"])print(c) # Counter({'south_market': 2, 'web': 2, 'north_market': 2})print(c.most_common(2)) # [('south_market', 2), ('web', 2)]print(sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))[:2]) # [('north_market', 2), ('south_market', 2)]print(c["promo"], "promo" in c) # 0 FalseCounter is a dict that counts. most_common(k) sorts by count, and for equal counts it keeps the order in which the keys first appeared. Here south_market came first, so north_market was dropped. That is not alphabetical, and the input order is rarely part of the task. When the task says how to break ties, sort with a tuple key: minus the count for descending, then the name. Tuple keys are explained on Sorting and top-k.
Unlike a defaultdict, a Counter returns 0 for a missing key and does not add it.
Latest per key: compare timestamps
Section titled “Latest per key: compare timestamps”Events often arrive out of order. Then the last row in the list is not the latest event:
from datetime import datetime as dt
events = [ ("s1", dt(2026, 9, 1), "active"), ("s1", dt(2026, 9, 5), "expired"), ("s1", dt(2026, 9, 3), "billing_issue"), # arrived late]
last_arrived = {}for sub_id, ts, status in events: last_arrived[sub_id] = statusprint(last_arrived) # {'s1': 'billing_issue'}
latest = {} # sub_id -> (ts, status)for sub_id, ts, status in events: if sub_id not in latest or ts > latest[sub_id][0]: latest[sub_id] = (ts, status)print({k: status for k, (ts, status) in latest.items()}) # {'s1': 'expired'}The rule is “keep the best so far”: a dict from the key to (timestamp, value). Replace the value only when the new timestamp is later. The comparison sign decides ties: with > the first of two equal timestamps stays, with >= the later one in the list wins. Ask which one the task wants.
This is one pass, O(n). Sorting by time first also works, but costs O(n log n). In SQL the same task is ROW_NUMBER or DISTINCT ON, see Top N per group.
Every key, even with zero
Section titled “Every key, even with zero”A loop over the rows can only produce keys that appear in the rows. When the task says “every product” or “every channel, even without sales”, loop over that side instead:
from collections import Counter
products = ["prd_03", "prd_09", "prd_12"]purchases = ["prd_03", "prd_09", "prd_03"]
counts = Counter(purchases)print(dict(counts)) # {'prd_03': 2, 'prd_09': 1} -- prd_12 is missingprint({p: counts.get(p, 0) for p in products}) # {'prd_03': 2, 'prd_09': 1, 'prd_12': 0}This is the Python form of LEFT JOIN with COALESCE(…, 0), see LEFT JOIN and zeros. Read with .get() in this loop: on a defaultdict, counts[p] would add an empty entry for every product without data.
Practice
Section titled “Practice”Given payments as dicts {'customer': str, 'amount': Decimal}, return a plain dict (not a defaultdict) customer -> total amount.
Data and an example
The checks run after your code and can use these:
from decimal import DecimalP = [{"customer": "c1", "amount": Decimal("9.99")}, {"customer": "c2", "amount": Decimal("4.99")}, {"customer": "c1", "amount": Decimal("0.01")}]Example: revenue_by_customer(P) → {'c1': Decimal('10.00'), 'c2': Decimal('4.99')}
2 checks. Your own print() output is shown too.
from decimal import Decimal
def revenue_by_customer(payments):
...
Show answer
Reference
from collections import defaultdictfrom decimal import Decimal
def revenue_by_customer(payments): totals = defaultdict(Decimal) for p in payments: totals[p["customer"]] += p["amount"] return dict(totals)Checks and the expected values
-
revenue_by_customer(P)→{'c1': Decimal('10.00'), 'c2': Decimal('4.99')} -
revenue_by_customer([])→{}
defaultdict(Decimal) starts each new customer at Decimal('0'), so the loop needs no if. Return dict(totals): a caller who reads a missing customer gets KeyError or None from .get(), and the result does not grow. Money is Decimal, never float.
rows are dicts {'start': datetime, 'amount': Decimal}. Return a plain dict 'YYYY-MM' -> total, months sorted.
Data and an example
The checks run after your code and can use these:
from datetime import datetime as dtfrom decimal import Decimal as DR = [{"start": dt(2026, 9, 2), "amount": D("9.99")}, {"start": dt(2026, 8, 31, 23, 59), "amount": D("4.99")}, {"start": dt(2026, 9, 30), "amount": D("1.00")}]Example: revenue_by_month(R) → {'2026-08': D('4.99'), '2026-09': D('10.99')}
2 checks. Your own print() output is shown too.
def revenue_by_month(rows):
...
Show answer
Reference
from collections import defaultdictfrom decimal import Decimal
def revenue_by_month(rows): totals = defaultdict(Decimal) for r in rows: totals[r["start"].strftime("%Y-%m")] += r["amount"] return dict(sorted(totals.items()))Checks and the expected values
-
revenue_by_month(R)→{'2026-08': Decimal('4.99'), '2026-09': Decimal('10.99')} -
list(revenue_by_month(R))→['2026-08', '2026-09']
The month key is start.strftime("%Y-%m"); (start.year, start.month) works too when the format is free. A dict keeps insertion order, so sort the items before you build the result. This is GROUP BY date_trunc('month', …) written in Python. The row at 23:59 on 31 August belongs to August.
Return the k most common channels as (channel, count) pairs; equal counts — alphabetical order.
Data and an example
Example: top_channels(['south', 'north', 'north', 'web', 'south'], 2) → [('north', 2), ('south', 2)]
3 checks. Your own print() output is shown too.
def top_channels(channels, k):
...
Show answer
Reference
from collections import Counter
def top_channels(channels, k): counts = Counter(channels) return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:k]Checks and the expected values
-
top_channels(['south', 'north', 'north', 'web', 'south'], 2)→[('north', 2), ('south', 2)] -
top_channels(['north'], 5)→[('north', 1)] -
top_channels([], 3)→[]
Counter counts, and the tuple key (-count, name) sets the order: count descending, then channel name ascending. On the first check most_common(2) returns [('south', 2), ('north', 2)], because south appears first in the input, so it fails. The slice [:k] also works when k is larger than the number of channels, as in the second check.
Events are (subscription_id, timestamp, status). Return subscription_id -> status of its latest event. Equal timestamps — the later one in the list wins.
Data and an example
The checks run after your code and can use these:
from datetime import datetime as dtEV = [("s1", dt(2026, 9, 1), "active"), ("s2", dt(2026, 9, 2), "active"), ("s1", dt(2026, 9, 5), "expired"), ("s1", dt(2026, 9, 3), "billing_issue"), ("s2", dt(2026, 9, 2), "refunded")]Example: latest_status(EV) → {'s1': 'expired', 's2': 'refunded'}
2 checks. Your own print() output is shown too.
def latest_status(events):
...
Show answer
Reference
def latest_status(events): best = {} for sub_id, ts, status in events: if sub_id not in best or ts >= best[sub_id][0]: best[sub_id] = (ts, status) return {sub_id: status for sub_id, (ts, status) in best.items()}Checks and the expected values
-
latest_status(EV)→{'s1': 'expired', 's2': 'refunded'} -
latest_status([])→{}
One pass with a dict of the best row so far. The events are out of order (for s1, the event of 5 September comes before the one of 3 September), so compare timestamps instead of taking the last row. >= lets the later of two equal timestamps win, as the task asks: that is the s2 case.
Stock on hand without a database. items: [{'id', 'name', 'unit_cost': Decimal}], moves: [{'item_id', 'moved_at': 'YYYY-MM-DD', 'qty'}] (qty is negative when stock goes out), cutoff: 'YYYY-MM-DD'. Return a list of (id, name, units, value) in the order of items, counting only moves before cutoff; value = unit_cost × units. An item with no moves gives (id, name, 0, Decimal('0.00')). A move for an item that is not in items raises ValueError.
Data and an example
The checks run after your code and can use these:
from decimal import DecimalITEMS = [{"id": 1, "name": "Notebook", "unit_cost": Decimal("3.50")}, {"id": 2, "name": "Pen", "unit_cost": Decimal("1.20")}, {"id": 3, "name": "Pen", "unit_cost": Decimal("0.80")}, {"id": 4, "name": "Stapler", "unit_cost": Decimal("7.00")}]MOVES = [{"item_id": 1, "moved_at": "2026-09-01", "qty": 40}, {"item_id": 1, "moved_at": "2026-09-10", "qty": -15}, {"item_id": 2, "moved_at": "2026-09-03", "qty": 100}, {"item_id": 2, "moved_at": "2026-09-20", "qty": -100}, {"item_id": 3, "moved_at": "2026-09-05", "qty": 25}, {"item_id": 3, "moved_at": "2026-10-01", "qty": 5}, {"item_id": 1, "moved_at": "2026-10-02", "qty": -5}]Example: stock_on_hand(ITEMS, MOVES, '2026-10-01') → [(1, 'Notebook', 25, Decimal('87.50')), (2, 'Pen', 0, Decimal('0.00')), (3, 'Pen', 25, Decimal('20.00')), (4, 'Stapler', 0, Decimal('0.00'))]
4 checks. Your own print() output is shown too.
from decimal import Decimal
def stock_on_hand(items, moves, cutoff):
...
Show answer
Reference
from collections import defaultdictfrom decimal import Decimal
def stock_on_hand(items, moves, cutoff): known = {i["id"] for i in items} units = defaultdict(int) # item id -> units before cutoff for m in moves: if m["item_id"] not in known: raise ValueError(f"move for unknown item {m['item_id']}") if m["moved_at"] < cutoff: # ISO dates compare as strings units[m["item_id"]] += m["qty"] return [(i["id"], i["name"], units[i["id"]], i["unit_cost"] * units[i["id"]]) for i in items]Checks and the expected values
-
stock_on_hand(ITEMS, MOVES, '2026-10-01')→[(1, 'Notebook', 25, Decimal('87.50')), (2, 'Pen', 0, Decimal('0.00')), (3, 'Pen', 25, Decimal('20.00')), (4, 'Stapler', 0, Decimal('0.00'))] -
stock_on_hand(ITEMS, [], '2026-10-01')→[(1, 'Notebook', 0, Decimal('0.00')), (2, 'Pen', 0, Decimal('0.00')), (3, 'Pen', 0, Decimal('0.00')), (4, 'Stapler', 0, Decimal('0.00'))] -
stock_on_hand([], [], '2026-10-01')→[] -
stock_on_hand(ITEMS, MOVES + [{'item_id': 9, 'moved_at': '2026-09-01', 'qty': 1}], '2026-10-01')→raises ValueError
Loop over the items, not over the moves: the stapler has no moves and still needs its row (4, 'Stapler', 0, Decimal('0.00')), the Python form of a LEFT JOIN. Key the units by id, never by name: two items are called Pen, and grouping by name would give one Pen with 25 units. Check every move against the known ids before the date filter, so a bad move raises ValueError whatever its date. The cutoff is excluded (moved_at < cutoff): the move of item 3 on 2026-10-01 falls on the cutoff and does not count. ISO dates in one format compare correctly as strings. unit_cost * 0 is already Decimal('0.00'), so the zero rows need no special code.
Further reading
Section titled “Further reading”- collections.defaultdict — the factory argument, with examples for
listandint. - collections.Counter — counting,
most_commonand the order of equal counts. - Mapping types — dict —
get,in,setdefaultand insertion order. - strftime() and strptime() format codes —
%Y-%mand other keys made from dates.
Related topics
Section titled “Related topics”- Sets and duplicates — the same hash table, for “have I seen this id?”.
- Sorting and top-k — tuple keys for ties, and top-k without a full sort.
- Money and Decimal — why the totals are
Decimal. - Grouping and counting — the same tasks with
GROUP BY. - LEFT JOIN and zeros — “every X, even with zero” in SQL.
- Iteration and generators — when the rows do not fit in memory.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.