Dictionaries as Tables
Dict Lookup Table
Build a code-to-name lookup dictionary from two parallel lists, then resolve
a batch of query codes — including one that is absent — using a guarded
membership test. The replay shows lookup growing one entry at a time and
result accumulating found names and the fallback value.
By hand
The Pythonic way
Write lookup as a dict literal and replace the if/else guard with
lookup.get(q, 'unknown'), which returns the fallback value in one
expression without a separate membership test.
naive.py
codes = ['r', 'g', 'b', 'y', 'w']
names = ['red', 'green', 'blue', 'yellow', 'white']
lookup = {}
for code, name in zip(codes, names):
lookup[code] = name
queries = ['r', 'b', 'x', 'y']
result = []
for q in queries:
if q in lookup:
result.append(lookup[q])
else:
result.append('unknown')
print('RESULT:', result)
library.py
lookup = {
'r': 'red', 'g': 'green', 'b': 'blue',
'y': 'yellow', 'w': 'white',
}
queries = ['r', 'b', 'x', 'y']
result = [lookup.get(q, 'unknown') for q in queries]
print('RESULT:', result)
RESULT: ['red', 'blue', 'unknown', 'yellow']
Implementation notes
d.get(key, default)is preferred overif key in d: d[key]when you only need the value and not the key's presence for branching; it is also slightly faster because it avoids a second hash lookup.- Dict lookup is O(1) average-case regardless of size, making it efficient for large tables where a linear list scan would be O(n).
- Key order in Python dicts is insertion order (guaranteed since 3.7); the
replay shows
lookupentries appearing in the order they were inserted.