runtime

compare approaches one problem · two ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Joining records: nested loops vs a dict index

Show each order with its customer's state.

what differs

The nested loop scans customers for every order; the dict hashes each lookup. With 8 orders it hardly matters; with 100,000 it's the difference between seconds and hours.

at a glance

approachuse it when
A · nested loopsA one-off lookup or two.
B · dict indexMany lookups by the same key: build the index once.

Watch out: If the key can be missing, the nested loop prints nothing for that order while state[...] raises KeyError; decide which behaviour you want.

the outputs

Each approach runs on the same input.

concepts

hash joinindex

learn it

Look up and merge by key

related comparisons

pandas merge vs SQL JOIN

Uses the Online Store dataset.

A · nested loops
B · dict index
Compare Python Approaches · Runtime