Data Structures · Dictionaries and Sets · lesson 7 of 10
Iterating over dictionaries
about 12 minutes · free · runs in your browser
Step 1 of 2
Keys, values and both
Three views onto a dictionary:
for key in scores: # keys — the default
for value in scores.values(): # values
for key, value in scores.items(): # both
.items() is the one you will use most. Since Python 3.7 dictionaries keep insertion
order, so iteration is predictable.
in checks for a key, not a value:
"Ada" in scores # True if Ada is a key
90 in scores.values() # check the values instead
Your turn: write best(scores) returning the name with the highest score. If the
dictionary is empty, return None.
You start from this, and edit it in the browser:
def best(scores):
# Return the name with the highest score, or None.
pass
Step 2 of 2
Transforming a dictionary
Dictionary comprehensions work just like list comprehensions, with a key: value pair
at the front:
doubled = {k: v * 2 for k, v in scores.items()}
Your turn: write passing(scores) returning a new dictionary containing only the
entries scoring 50 or more. Leave the original untouched.
You start from this, and edit it in the browser:
def passing(scores):
# Return only the entries scoring 50 or more.
pass