7. Iterate
A for loop repeats a block once for each element of a collection:
itemis a name you choose; it holds the current element on each pass.collectionis anything iterable: a list, a string, a dictionary view…- The block is indented below the colon, like the body of an
if.
A dictionary is iterable over its keys:
To repeat over the values, loop over person.values(). To get both the key and the value, loop over person.items() and unpack each (key, value) pair into two names:
The loop follows the dictionary's insertion order.
Coming from JavaScript? for key in d iterates keys, like for...in, not values. Use d.items() for key/value pairs, like Object.entries().
Loop over the keys
Create person = {"name": "Ada", "age": 36}. Loop over the dictionary with a for loop and print each key, one per line. A dictionary is iterable over its keys.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Loop over the values
With the same person = {"name": "Ada", "age": 36}, loop over person.values() and print each value, one per line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Loop over key and value
Loop over person.items() with for key, value in ... and print each pair as key: value using an f-string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Filter while looping
Create scores = {"math": 90, "art": 60, "science": 85}. Loop over scores.items() with an if inside the loop and print only the subject names whose score is 80 or more, one per line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.