Maps and hashing

A dict as a map from key to value — average-case lookup.

A map sends a key to a value. Python’s dict is a hash map: average lookup does not walk the whole list. That is why city in prices on a dict is usually cheaper than scanning.

Goal

Build a price map, look up keys, and count a linear scan versus dict access.

A map

price = {"A": 10.5, "B": 22.0, "C": 31.0}
print(price["B"])
print("D" in price)
print(price.get("D", 0.0))

Scan vs map

rows = [("A", 10.5), ("B", 22.0), ("C", 31.0), ("A", 10.5)]

def lookup_scan(pairs, key):
    steps = 0
    found = None
    for k, v in pairs:
        steps += 1
        if k == key:
            found = v
            break
    return found, steps

price = dict(rows[-3:])  # last wins if duplicate keys — here just a map
print("scan B", lookup_scan(rows, "B"))
print("map B", price["B"])
print("keys", sorted(price))

The scan may check several pairs. The dict lookup does not show a step count because hashing is inside the interpreter — treat it as “about constant” for this course.

Count with a map

cities = ["Nairobi", "Mombasa", "Nairobi", "Kisumu", "Nairobi"]
counts = {}
for city in cities:
    counts[city] = counts.get(city, 0) + 1
print(counts)
Tip

Keys must be immutable: strings, numbers, tuples of those. A list cannot be a dict key.