Looking up a value by its key
A dictionary maps keys to values, and the main reason to build one is to look values up again. You do that by writing the key in square brackets after the dictionary's name:
scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
alice_score = scores["Alice"]
bob_score = scores["Bob"]
print(alice_score, bob_score) # 95 87
The lookup does not remove anything: scores still holds all three pairs afterwards. The result is an ordinary value, and you can store it in a variable, print it or use it in a calculation. Lookups are fast, because Python finds the key directly instead of scanning the dictionary from the start.
The key you write must match exactly. Keys are case sensitive, so scores["alice"] is not scores["Alice"], and a number key is not the same as a text key that looks like it.
Using looked-up values
A looked-up value behaves like any other value of its type, so you can compare it, add it to another one or print it. Looking up a key is also the usual way to read every entry: loop over the keys and look each one up.
print(scores["Alice"] + scores["Bob"]) # 182
print(scores["Alice"] > scores["Bob"]) # True
for name in scores:
print(name, scores[name])
182
True
Alice 95
Bob 87
Charlie 72
Looping over a dictionary gives its keys, in the order they were added. Inside the loop, scores[name] is safe because every key comes from the dictionary itself. The loop for name, score in scores.items(): gives you both at once and avoids the second lookup.
When the key is missing
If the key does not exist, square brackets raise a KeyError and the program stops:
try:
scores["Diana"]
except KeyError as error:
print("KeyError:", error)
KeyError: 'Diana'
Often a missing key is not a bug, and you want to carry on. Python gives you two ways to handle it.
The get() method
get() takes the key and, as an optional second argument, a default to use when the key is missing. It never raises an error:
print(scores.get("Alice", 0)) # 95
print(scores.get("Diana", 0)) # 0
print(scores.get("Diana")) # None
Without the second argument, a missing key gives None, Python's value for "nothing here". Notice that get() does not add the missing key to the dictionary. It only reads.
Checking with in
The in operator tells you whether a key exists, so you can decide what to do before looking it up:
if "Alice" in scores:
print(scores["Alice"]) # 95
print("Diana" in scores) # False
The operator checks the keys, not the values. 95 in scores is False, even though 95 is one of the values. To look among values, use 95 in scores.values(), which is True.
Which one to use
- Use
d[key]when the key must be there. AKeyErrorthen points straight at the bug, instead of letting a wrong value slip through. - Use
d.get(key, default)when a missing key is normal and a fallback value makes sense, for example counting withcounts.get(word, 0) + 1. - Use
key in dwhen the program should take a different path depending on whether the key exists.
Common mistakes
- Using parentheses. A dictionary is not called.
scores("Alice")raises aTypeError; lookups use square brackets. - Forgetting the quotes.
scores[Alice]looks for a variable namedAlice. The key is the string"Alice". - Treating a number key as text. If the keys are integers, write
d[1], notd["1"]. - Using a default of the wrong kind. A fallback of
0makes sense for scores, but later code that expects text could break if it receivesNone.
The exercise, step by step
The lesson starts with the scores dictionary already written and asks for Alice's score.
- Write the lookup. Put
"Alice"in square brackets afterscores. The key exists, so the lookup is safe andget()is not needed. - Store it. Assign the value to a new variable named
alice_score, below the dictionary.
scores = {"Alice": 95, "Bob": 87, "Charlie": 72}
alice_score = scores["Alice"]
Now alice_score is the number 95. The dictionary is unchanged, and you can look up the other students the same way.
Key takeaways
d[key]returns the value for a key and raisesKeyErrorif the key is missing.d.get(key, default)returns the default instead, orNoneif you give none.key in dchecks keys, not values.- Keys must match exactly, including case.