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
| approach | use it when |
|---|---|
| A · nested loops | A one-off lookup or two. |
| B · dict index | Many 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
related comparisons