Hone

Lessons · Python · dict lookup is fast

Why a dict finds things instantly

A dict jumps straight to a key; a list has to look at items one by one until it finds a match.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Ten items, no difference. A million users, and 'is this email taken?' is instant with a dict or set and a coffee break with a list. This is the single most common performance fix in real code.

How to think about it

Is this 'in' check inside a loop? Whenever you write 'x in some_list' inside a loop, stop. If the list is large or the loop runs many times, build a set (or dict) once, and check membership in that.

Worked example

banned = {"spam@x.com", "bot@y.org"}
A set: curly braces, no colons. Membership is a direct jump.
for email in incoming:
Maybe thousands of emails.
    if email in banned:
Instant per check, however big banned grows.
        block(email)
Same code with banned as a list would scan the whole list every time.

Your turn

Turn a list of allowed ids into something with instant lookup.

allowed = ([101, 205, 330])
if user_id in allowed:
    admit()

The trap

Sets and dict keys must be hashable: strings, numbers, tuples are fine; lists are not.

Practise dict lookup is fast on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.