Skip to content

Python dictionaries: store and look up data by key

You will build a short daily order report for an invented shop, OrdersPortal. Starting from a list of order records, it indexes orders by ID, groups them by customer, totals revenue and counts orders per status, then prints the result as JSON. Along the way you will learn to:

  • create dictionaries and read values safely with d[key], d.get(key) and in;
  • add, update, merge (|) and remove entries;
  • loop over keys, values and key-value pairs, and avoid changing a dict while looping over it;
  • build dicts with comprehensions, dict() and zip();
  • group and count with setdefault, collections.defaultdict and collections.Counter;
  • choose valid keys, and tell “missing” from “stored as None”.
  • Python 3.9 or later (the | merge operator arrived in 3.9). The outputs on this page come from CPython 3.14.6, the current release.
  • You know variables, lists and loops.

How to run the samples: save each sample as a .py file and run python3 file.py (on Windows, py file.py). Every sample is complete and shows its output.

A dictionary (dict) maps keys to values. Think of a real dictionary: you look up a word (the key) to find its definition (the value), without reading every page. Python’s dict works the same way: looking up a key takes about the same time whether the dict has ten entries or ten million, because it is a hash table.

Two rules shape everything else on this page:

  • Keys must be hashable, which in practice means immutable: strings, numbers, tuples of immutable values. Values can be anything.
  • Dicts remember insertion order. This has been guaranteed since Python 3.7. Updating an existing key keeps its position; a key deleted and added again goes to the end.
order = {
"id": "ORD-1001",
"email": "ada@example.test",
"amount": 149.99,
"status": "pending",
}
print(order["email"]) # KeyError if the key is missing
print(order.get("discount", 0.0)) # default instead of an error
print(order.get("notes")) # default default is None
print("amount" in order, "discount" in order)
print(len(order))
try:
order["discount"]
except KeyError as exc:
print("KeyError:", exc)
# Other ways to build a dict
print(dict(id="ORD-1002", amount=20.0))
print(dict([("ORD-1", 10.0), ("ORD-2", 20.0)]))
print(dict.fromkeys(["pending", "shipped"], 0))

Output:

ada@example.test
0.0
None
True False
4
KeyError: 'discount'
{'id': 'ORD-1002', 'amount': 20.0}
{'ORD-1': 10.0, 'ORD-2': 20.0}
{'pending': 0, 'shipped': 0}

Use order["email"] when the key must be there: a KeyError points straight at the bug. Use order.get("discount", 0.0) when the key is optional and a default makes sense. in checks keys, not values.

Check your work: what does order.get("status", "unknown") return? ('pending', because the key exists and the default is ignored.)

order = {"id": "ORD-1001", "amount": 149.99, "status": "pending"}
order["status"] = "confirmed" # update an existing key
order["tracking"] = "TRK-0001" # add a new key
print(order)
del order["tracking"] # KeyError if missing
status = order.pop("status") # remove and return
missing = order.pop("discount", None) # no error with a default
print(status, missing, order)
order.update({"amount": 159.99, "notes": "gift wrap"})
print(order)
defaults = {"currency": "USD", "status": "pending"}
print(defaults | order) # merge: right-hand side wins (3.9+)
order |= {"status": "paid"} # in-place merge
print(order)

Output:

{'id': 'ORD-1001', 'amount': 149.99, 'status': 'confirmed', 'tracking': 'TRK-0001'}
confirmed None {'id': 'ORD-1001', 'amount': 149.99}
{'id': 'ORD-1001', 'amount': 159.99, 'notes': 'gift wrap'}
{'currency': 'USD', 'status': 'pending', 'id': 'ORD-1001', 'amount': 159.99, 'notes': 'gift wrap'}
{'id': 'ORD-1001', 'amount': 159.99, 'notes': 'gift wrap', 'status': 'paid'}

Assignment with d[key] = value both adds and updates. defaults | order builds a new dict where values from the right-hand side win, a tidy way to fill in defaults; |= and update() change the dict in place.

stock = {"MUG-01": 12, "PEN-02": 0, "CAP-03": 5}
for sku in stock: # iterating a dict gives its keys
print(sku, end=" ")
print()
for sku, qty in stock.items(): # key and value together
print(f"{sku}: {qty}")
print(sum(stock.values()))
keys = stock.keys() # a live view, not a copy
stock["BAG-04"] = 3
print(keys)
try:
for sku, qty in stock.items():
if qty == 0:
del stock[sku]
except RuntimeError as exc:
print("RuntimeError:", exc)
for sku in list(stock): # iterate over a copy of the keys
if stock[sku] == 0:
del stock[sku]
print(stock)

Output:

MUG-01 PEN-02 CAP-03
MUG-01: 12
PEN-02: 0
CAP-03: 5
17
dict_keys(['MUG-01', 'PEN-02', 'CAP-03', 'BAG-04'])
RuntimeError: dictionary changed size during iteration
{'MUG-01': 12, 'CAP-03': 5, 'BAG-04': 3}

.items() is the loop you will write most often. keys(), values() and items() return views that reflect later changes, which is why keys shows BAG-04. Deleting or adding keys while looping raises RuntimeError; notice the first del had already happened before the error. Loop over list(stock) instead, or build a new dict with a comprehension (next step).

A dict comprehension {key: value for item in iterable if condition} builds a new dict in one expression.

prices = {"MUG-01": 8.50, "PEN-02": 1.20, "CAP-03": 14.00, "BAG-04": 0.90}
expensive = {sku: p for sku, p in prices.items() if p > 5}
discounted = {sku: round(p * 0.9, 2) for sku, p in prices.items()}
by_price = dict(sorted(prices.items(), key=lambda kv: kv[1]))
print(expensive)
print(discounted)
print(by_price)
skus = ["MUG-01", "PEN-02"]
names = ["Mug", "Pen"]
print(dict(zip(skus, names)))

Output:

{'MUG-01': 8.5, 'CAP-03': 14.0}
{'MUG-01': 7.65, 'PEN-02': 1.08, 'CAP-03': 12.6, 'BAG-04': 0.81}
{'BAG-04': 0.9, 'PEN-02': 1.2, 'MUG-01': 8.5, 'CAP-03': 14.0}
{'MUG-01': 'Mug', 'PEN-02': 'Pen'}

Because dicts keep insertion order, dict(sorted(...)) gives a dict ordered by price. dict(zip(keys, values)) pairs two lists; see zip for what happens when they differ in length.

Grouping (“all orders per customer”) and counting (“how many of each tag”) are so common that Python offers three tools.

from collections import Counter, defaultdict
orders = [
("ada@example.test", "ORD-001"),
("lin@example.test", "ORD-002"),
("ada@example.test", "ORD-003"),
]
# setdefault: insert a default the first time a key is seen
by_customer: dict[str, list[str]] = {}
for email, order_id in orders:
by_customer.setdefault(email, []).append(order_id)
print(by_customer)
# defaultdict: the same, with the default built in
grouped = defaultdict(list)
for email, order_id in orders:
grouped[email].append(order_id)
print(dict(grouped))
# Counter: counting is so common it has its own dict subclass
tags = ["sale", "gift", "sale", "clearance", "sale", "gift"]
counts = Counter(tags)
print(counts.most_common(2), counts["missing"])

Output:

{'ada@example.test': ['ORD-001', 'ORD-003'], 'lin@example.test': ['ORD-002']}
{'ada@example.test': ['ORD-001', 'ORD-003'], 'lin@example.test': ['ORD-002']}
[('sale', 3), ('gift', 2)] 0

defaultdict(list) calls list() to create a value for any missing key, so you can append straight away. Be aware that even reading a missing key adds it. Counter returns 0 for missing keys instead of raising KeyError. The collections module page covers both in depth.

inventory = {("MUG-01", "blue"): 4} # tuples of hashable values work as keys
print(inventory[("MUG-01", "blue")])
try:
inventory[["MUG-01", "red"]] = 2
except TypeError as exc:
print("TypeError:", exc)
flags = {1: "one", True: "yes", 1.0: "float"}
print(flags) # 1, True and 1.0 are equal, so one key
sentinel = object()
settings = {"coupon": None}
print(settings.get("coupon") is None, settings.get("missing") is None)
print(settings.get("coupon", sentinel) is sentinel, settings.get("missing", sentinel) is sentinel)

Output:

4
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
{1: 'float'}
True True
False True

A list cannot be a key because it can change after it is stored; use a tuple. Keys that compare equal are the same key, so 1, True and 1.0 collapse into one entry (the first key is kept, the last value wins). And get() returns None both for a missing key and for a key stored with the value None; use in, or a unique sentinel object as the default, to tell them apart.

The daily report puts the steps together.

"""OrdersPortal daily report: index raw orders by customer and summarize."""
import json
from collections import Counter, defaultdict
raw_orders = [
{"id": "ORD-001", "email": "ada@example.test", "amount": 149.99, "status": "shipped"},
{"id": "ORD-002", "email": "lin@example.test", "amount": 49.99, "status": "pending"},
{"id": "ORD-003", "email": "ada@example.test", "amount": 299.00, "status": "shipped"},
{"id": "ORD-004", "email": "sam@example.test", "amount": 15.50, "status": "cancelled"},
{"id": "ORD-005", "email": "lin@example.test", "amount": 80.00, "status": "shipped"},
]
# 1. Look up any order by id in O(1) on average.
orders_by_id = {order["id"]: order for order in raw_orders}
# 2. Group orders by customer.
by_customer: defaultdict[str, list[dict]] = defaultdict(list)
for order in raw_orders:
by_customer[order["email"]].append(order)
# 3. Revenue per customer, ignoring cancelled orders.
revenue = {
email: round(sum(o["amount"] for o in orders if o["status"] != "cancelled"), 2)
for email, orders in by_customer.items()
}
# 4. How many orders are in each status.
status_counts = Counter(order["status"] for order in raw_orders)
report = {
"lookup": orders_by_id["ORD-003"]["amount"],
"revenue": dict(sorted(revenue.items(), key=lambda kv: kv[1], reverse=True)),
"status_counts": dict(status_counts),
"top_customer": max(revenue, key=revenue.get),
}
print(json.dumps(report, indent=2))

Output:

{
"lookup": 299.0,
"revenue": {
"ada@example.test": 448.99,
"lin@example.test": 129.99,
"sam@example.test": 0
},
"status_counts": {
"shipped": 3,
"pending": 1,
"cancelled": 1
},
"top_customer": "ada@example.test"
}

max(revenue, key=revenue.get) finds the key with the largest value: iterating a dict yields keys, and revenue.get maps each key to its value. json.dumps turns the nested dicts into JSON text, which is how dicts usually leave a Python program. (The sam total prints as 0 because sum() of nothing is the integer 0.)

  • Using d[key] for optional data. It raises KeyError. Use get() with a default, or check in first.
  • Changing a dict while looping over it. Loop over list(d) or build a new dict with a comprehension.
  • Using a list or dict as a key. They are unhashable; use a tuple or a frozenset.
  • Treating get(key) is None as “missing”. A stored None looks the same. Use key in d.
  • Sharing one mutable default. dict.fromkeys(skus, []) gives every key the same list. Use a comprehension {s: [] for s in skus} or defaultdict(list).
  • Copying with =. b = a makes a second name for the same dict. Use a.copy() or dict(a) for a shallow copy, and see copy vs deepcopy for nested data.
Error (Python 3.14) Cause Fix
KeyError: 'discount' Reading a key that is not there get("discount", default) or check in first; check spelling and case.
TypeError: cannot use 'list' as a dict key (unhashable type: 'list') A list used as a key Convert to a tuple. Python 3.13 and older print TypeError: unhashable type: 'list'.
RuntimeError: dictionary changed size during iteration Adding or deleting keys inside a loop over the dict Loop over list(d).
TypeError: unsupported operand type(s) for |: 'dict' and 'dict' Using | on Python 3.8 or older Upgrade, or use {**a, **b}.
AttributeError: 'dict' object has no attribute 'email' Writing order.email Dicts use order["email"]; for attribute access use a dataclass.

1. Why is looking up a key in a dict fast, and what does that require of keys? A dict is a hash table: Python hashes the key to find its slot, so a lookup takes constant time on average. Keys therefore need a stable hash and a consistent ==, which is why they must be immutable (hashable).

2. What is the difference between d[key], d.get(key) and d.setdefault(key, default)? d[key] raises KeyError if the key is missing. get returns a default (normally None) and leaves the dict unchanged. setdefault returns the existing value or inserts the default and returns it.

3. Are dicts ordered? Yes. Since Python 3.7 the language guarantees insertion order. Equality between two plain dicts still ignores order: {"a": 1, "b": 2} == {"b": 2, "a": 1} is True.

4. You need to count how often each product appears in a million order lines. What do you use? collections.Counter(lines). It is a dict subclass designed for counting, returns 0 for unseen keys and has most_common(). A plain dict with get(key, 0) + 1 works too, but is more code for the same result.

Dicts often hold lists and other dicts; comprehensions let you build those structures in one step. When you need a fixed set of fields with names, move on to dataclasses or named tuples, and when you need unique items without values, use sets.

  • Lists and tuples: the ordered sequences that dicts often contain or use as keys.
  • Sets: hash-based collections of unique keys without values.
  • Data structures tutorial: lists, tuples, dicts and sets compared.
  • collections module: defaultdict, Counter, OrderedDict and ChainMap.
  • OrderedDict: what it still offers now that dicts are ordered.
  • ChainMap: layered lookups across several dicts.