Dictionaries in Python: look things up by key
Some data isn't a line-up — it's a lookup. A dictionary stores pairs, so you can ask for a value by its key, like reading an amino acid straight from its codon.
The big idea
A dictionary maps keys to values, letting you fetch a value instantly by its key instead of its position.
See it in code
A dictionary stores key: value pairs in { }. Here two codons map to their amino acids, and codon_table["AUG"] fetches one straight by its key:
codon_table = {"AUG": "Met", "UUU": "Phe"}
print(codon_table["AUG"])Met
No searching, no index — ["AUG"] went right to "Met". That instant lookup is the whole point.
len() counts the pairs, and any key you know fetches its value. Same table, two questions asked of it:
codon_table = {"AUG": "Met", "UUU": "Phe"}
print("Codons known:", len(codon_table))
print("UUU codes for:", codon_table["UUU"])Codons known: 2 UUU codes for: Phe
Two pairs, and ["UUU"] reached the second one directly. Now let's grow the table and loop over several codons.
In biology, each three-letter codon codes for an amino acid — a perfect dictionary. We add GGC, then loop a list of codons, looking each one up by key:
codon_table = {
"AUG": "Met",
"UUU": "Phe",
"GGC": "Gly",
}
print("AUG codes for:", codon_table["AUG"])
print("Codons known:", len(codon_table))
for codon in ["AUG", "GGC"]:
print(codon, "->", codon_table[codon])AUG codes for: Met Codons known: 3 AUG -> Met GGC -> Gly
A list would make you search for the right pair; the dictionary jumps to it by key in one step — even inside a loop. Keys are unique and must be immutable (strings and numbers work); values can be anything.
Dictionaries model any 'look up X by Y': a player's stats by name, a config of settings, word counts in a text, a cache of results. When your data is labeled rather than ordered, reach for a dictionary — the lookup stays fast even with millions of keys.
Try it yourself
Add "UAA": "Stop" to the table, then look it up. Next, guard a missing key with codon_table.get("XYZ", "unknown"), and loop the pairs with for k, v in codon_table.items():.
The common mistake
Indexing a key that isn't there. codon_table["XYZ"] raises KeyError and stops the program. When a key might be missing, use .get(key, default), which returns your fallback instead of crashing.
What it unlocks
Key-value lookups power the genetic code and transcription and translation, and complement ordered lists.