🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Python Dictionaries: Counters, Groups, and Merging

Python Data Structures🟢 Free Lesson

Python Dictionaries: Counters, Groups, and Merging

The dictionary is Python's most-used data structure precisely because it does so many jobs at once: record, cache, index, dispatch table, and tally. That flexibility is also why dictionary code rots quietly. A configuration reader grows nested brackets until a missing key raises at three in the morning, a frequency counter accumulates defensive if key in counts lines, and a chain of elif branches hides inside what should have been a lookup. This lesson treats the dictionary as a design tool: how its guarantees actually work, how to reach into nested data without exceptions, how the collections module removes boilerplate, and how to turn branching logic into table lookups you can test.

What You'll Learn

  • 1State the guarantees dict makes about keys, ordering, and uniqueness
  • 2Read nested configuration safely instead of catching KeyError everywhere
  • 3Count and group with defaultdict and Counter, including Counter arithmetic
  • 4Replace conditional chains with dispatch dictionaries and know when that hurts

What dict actually guarantees

A dictionary key must be hashable, which rules out lists and other dictionaries but admits strings, numbers, tuples of hashables, and frozen sets. Two keys that compare equal must hash equal, so 1, 1.0, and True all collide on the same slot — a fact that surprises code mixing numeric types, because the last write wins and the key's original type may be the one you did not expect. Lookup, insertion, and deletion are all constant time on average, driven by the hash of the key rather than by how many entries exist.

Since Python 3.7 the language also guarantees that iteration follows insertion order, and 3.6 already delivered that in practice as a CPython implementation detail. Ordering is a property of the container, not a sort: writing entries in a scrambled order preserves that scramble. When order matters semantically, build the dict deliberately or sort at read time.

python
record = {"id": 101, "name": "Ada", "active": True}

print(record["name"])                 # Ada
print(record.get("missing", "n/a"))   # n/a — no exception
print(1 in record, "1" in record)     # False True — type matters
print(1 == 1.0, hash(1) == hash(1.0)) # True True — same slot

ordered = dict.fromkeys(["step", "load", "store"])
print(list(ordered))                  # ['step', 'load', 'store']

keys = ["a", "b", "c"]
values = [1, 2, 3]
print(dict(zip(keys, values)))        # {'a': 1, 'b': 2, 'c': 3}

The zip idiom above is the fastest way to pair two parallel sequences, and dict.fromkeys gives you a dictionary of defaults in one call — as long as the default is immutable, since every key would otherwise share the same object.

Reaching into nested configuration

Configuration data, JSON responses, and ORM results arrive as nested dictionaries, and the naive access pattern multiplies brackets and try blocks. Three approaches exist in increasing order of robustness. First, dict.get with a default, which works for one level and becomes unreadable beyond two. Second, a small helper that walks a path of keys and returns a default on the first miss — explicit, dependency-free, and easy to test. Third, defensive normalisation: flatten or validate the structure once at the boundary, then use ordinary indexing everywhere else.

The third option is the one that scales, because it moves error handling out of the hot path and into a single place where a malformed payload can be rejected with a useful message. The helper remains valuable for ad-hoc queries where normalising the whole structure would be more work than the lookup itself.

python
def dig(mapping, path, default=None):
    current = mapping
    for key in path:
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    return current

config = {
    "database": {"host": "localhost", "port": 5432,
                 "credentials": {"user": "admin", "token": "abc123"}},
    "feature_flags": {},
}

print(dig(config, ["database", "host"]))                 # localhost
print(dig(config, ["database", "credentials", "user"]))  # admin
print(dig(config, ["feature_flags", "new_ui"], False))   # False
print(dig(config, ["database", "timeout"], 30))          # 30

A note on defaults: never use a mutable object — an empty list or an empty dictionary — as a get default, because the same instance is handed to every caller and one caller's append is everybody's data. dig sidesteps this by returning a caller-supplied default rather than creating one per call.

Counting and grouping without boilerplate

Before collections, counting meant a three-line pattern repeated in every file: check whether the key exists, initialise it if not, then increment. defaultdict collapses that into a factory call, and Counter goes further by adding ranking and arithmetic. Grouping works the same way — a defaultdict(list) turns a stream of pairs into buckets without a single membership test.

Counter behaves like a multiset. most_common(n) ranks entries, elements with non-positive counts disappear when you subtract, and adding two counters merges them by summing shared keys. That arithmetic makes it easy to compare corpora: difference for exclusive tokens, intersection for shared ones, and union for coverage.

python
from collections import Counter, defaultdict

words = "the cat sat on the mat the cat".split()
counts = Counter(words)
print(counts.most_common(2))          # [('the', 3), ('cat', 2)]
print(counts["dog"])                  # 0 — missing keys read as zero

pairs = [("alice", "math"), ("bob", "science"),
         ("alice", "science"), ("carol", "math")]
groups = defaultdict(list)
for student, subject in pairs:
    groups[subject].append(student)
print(dict(groups))                   # {'math': [...], 'science': [...]}

week1 = Counter({"red": 12, "blue": 9})
week2 = Counter({"red": 5, "green": 4})
print(week1 + week2)                  # Counter({'red': 17, 'blue': 9, 'green': 4})
print(week1 - week2)                  # Counter({'red': 7, 'blue': 9})
print(list(week1 & week2))            # ['red']

Watch one trap when counting unhashable items: a list cannot be a key, so tally derived identifiers such as item["id"] or tuple(sorted(item)) instead. And if you only ever read counts that might be absent, plain Counter is preferable to defaultdict(int), because Counter returns zero for unknown keys without inserting them and inflating the table.

Merging, inverting, and filtering

Merging dictionaries looks trivial until precedence matters. The ** unpacking operator and the | operator (Python 3.9 and later) both produce a new dictionary in which later sources win, while update mutates the left operand in place. A three-line rule covers the cases: use | for a one-off combination, update when you are progressively filling a result you own, and collections.ChainMap when you need layered defaults without copying anything.

Inversion is a one-line dictionary comprehension — but only safe when values are unique and hashable. Duplicate values silently collapse to the last key, so decide the policy first: keep the first, keep the last, or group every key that shares a value. Filtering and sorting follow the same comprehension shape, and dict(sorted(...)) is the idiomatic way to materialise a value-ordered mapping.

python
defaults = {"timeout": 30, "retries": 3, "debug": False}
loaded = {"timeout": 10, "region": "eu"}

merged = defaults | loaded            # Python 3.9+
print(merged)                         # loaded wins on timeout
defaults.update(loaded)               # in-place variant

inverted = {v: k for k, v in {"a": 1, "b": 2}.items()}
print(inverted)                       # {1: 'a', 2: 'b'}

big = {"c": 3, "a": 1, "b": 2}
print({k: v for k, v in big.items() if v >= 2})   # {'c': 3}
print(dict(sorted(big.items(), key=lambda kv: kv[1])))
# {'a': 1, 'b': 2, 'c': 3}

For read-only layered configuration, ChainMap avoids the copy entirely: it holds a list of mappings and checks them in order, falling through to the next when a key is absent. Writes go to the first mapping only, which is exactly the behaviour you want for command-line arguments layered over environment variables layered over a config file.

Dictionaries as dispatch tables

Long if/elif chains that compare a command or type string are really lookup tables in disguise, and they carry three costs: every branch is evaluated until one matches, adding a new case means editing the middle of the chain, and the branches cannot be inspected or tested as data. A dispatch dictionary inverts all three. The keys are the cases, the values are callables, and a single .get handles both the hit and the miss.

Dispatch also composes with functools.partial or lambdas when handlers need arguments, and it lets you register handlers from plugins without touching the dispatcher. The pattern is not free: when branches carry complex conditions rather than exact matches, or when you need elif chains expressed in plain English for non-programmers to review, a chain of conditionals remains clearer than a table.

python
import time

def compress(payload):
    return payload.upper()

def checksum(payload):
    return sum(payload.encode()) % 255

def audit(payload):
    time.sleep(0)
    return f"audited:{payload}"

PIPELINES = {
    "compress": compress,
    "checksum": checksum,
    "audit": audit,
}

def run(step, payload):
    handler = PIPELINES.get(step)
    if handler is None:
        raise KeyError(f"unknown step {step!r}, have {sorted(PIPELINES)}")
    return handler(payload)

print(run("compress", "hello"))    # HELLO
print(run("checksum", "hello"))    # 532
print(sorted(PIPELINES))           # ['audit', 'checksum', 'compress']

A registry like PIPELINES is also a natural place to enforce contracts: validate that every registered value is callable at registration time, and raise on unknown keys with a message that lists the valid ones. Both habits turn a runtime confusion into an error you see the first time you run the code.

How much does a dict cost?

Dictionaries are optimised for the common case, and knowing the shape of that case explains most performance advice. A dict is an open-addressed hash table that starts small and resizes by roughly doubling when it fills, at which point every key is rehashed — so building a dict by repeated update calls of small batches costs more than building it once from a list of pairs. Memory is the other axis: an empty dict has a fixed overhead that dwarfs a few small entries, so a dict per record is expensive when the records number in the millions.

TaskPreferred structureWhy
Exact-key lookup, stable schemadictFastest, ordered, built in
Grouping a stream by keydefaultdict(list)No existence checks in the loop
Frequency rankingCountermost_common and set arithmetic built in
Layered defaults, read-heavyChainMapNo copying; writes go to one layer
Many small recordsdataclass or tupleFar less per-object overhead than a dict
Keys are unhashablenormalise to tuplesKeeps O(1) lookup instead of scanning a list

If a dictionary holds hundreds of thousands of records that are mostly static, consider converting it to two parallel arrays or to a tuple sorted by key with bisect for lookups: build cost moves to start-up, and memory drops sharply. For everything else, plain dict operations are already close to the metal, and the real optimisation is usually reducing the number of lookups rather than making each one faster.

Common Mistakes

Catching KeyError around every nested read instead of validating the shape once

Fix: Normalise or flatten the payload at the boundary, then index directly — or use a dig helper with a default

Using a mutable default such as [] with dict.get or dict.fromkeys

Fix: Pass None and create the fresh object after the lookup, so callers never share state

Reversing a dictionary with a comprehension without checking for duplicate values

Fix: Confirm values are unique and hashable, or group keys per value explicitly

Assuming a defaultdict never grows unexpectedly

Fix: Remember that reading a missing key inserts it; use Counter when absent keys should read as zero without being stored

Replacing an if and elif chain whose conditions overlap

Fix: Dispatch tables need mutually exclusive exact keys; keep a real conditional chain for range or pattern conditions

Best Practices

  • Validate or normalise nested payloads once at the boundary of your program
  • Prefer dict.get or a dig helper for optional keys, and raise only for genuinely required ones
  • Build large dictionaries in a single constructor call to pay the resize cost only once
  • Use zip to pair parallel sequences and dict.fromkeys for immutable defaults
  • Keep dispatch tables as module-level data so they can be inspected and tested

Interview Questions

Q1: What are the requirements for a dictionary key?

The key must be hashable — its hash must not change while it is stored — and equal keys must produce equal hashes. Strings, numbers, tuples of hashables and frozen sets qualify; lists and dicts do not.

Q2: Difference between dict.get and a direct index when the key may be absent?

Direct indexing raises KeyError, which is appropriate when the key is required. get returns a supplied default and never raises, which suits optional fields. Neither distinguishes a missing key from one explicitly set to None unless you pass a sentinel.

Q3: How would you merge three dictionaries with later sources winning?

With the | operator: a | b | c, available from Python 3.9. Before 3.9 use {**a, **b, **c}. Both create a new dictionary, so the sources are untouched; update mutates instead.

Key Takeaways

  • Dict keys must be hashable and unique; 1 and 1.0 share a slot because they hash equally
  • Insertion order is guaranteed since Python 3.7 but is never automatically sorted
  • defaultdict removes existence checks, Counter adds ranking and arithmetic
  • Merging with | or ** precedence gives later sources priority; ChainMap layers without copying
  • Dispatch tables beat elif chains for exact matches, while overlapping conditions still need conditionals
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement