Dictionaries – Iteration, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
Dictionaries – Iteration in one minute
What students need to know
.items() provides (key, value) tuples. k, v unpacks each pair. 'in' checks if a key exists in the dict — prevents KeyError.
Iterating a dict directly gives you the keys — same as for key in d.keys():. You must call .values() explicitly — for v in d: gives keys, not values.
Mistakes students make
- Looping over d directly gives only keys. Use .items() for key-value pairs.
- for val in d: gives KEYS, not values. Use .values() for values.
- .keys() only gives keys. Use .items() to get both key and value.
- Without unpacking, k is a tuple like ('a', 1). Use k, v to unpack.
PREVIOUS · MODULE 38Dictionaries – Methods (keys, values, items, get)
YOU ARE HERE · MODULE 39Dictionaries – Iteration
NEXT · MODULE 40Sets – Basics
What students will learn in this module
Every question in Module 39
Quick questions
- for key in d: what does key get?AEach key, one at a timeBEach value
- How do you loop through values?Afor v in d.values():Bfor v in d:
- How do you loop through keys AND values?Afor k, v in d.items():Bfor k, v in d:
- d = {'a':1, 'b':2}\nfor k in d:\n print(k)\nWhat prints?A1 then 2Ba then b
- d = {'x':10}\nfor k, v in d.items():\n print(k, v)\nWhat prints?AxBx 10
Key terms
Students type the meaning of:
for key in d:for v in d.values():for k, v in d.items():'key' in d
Match the pairs
d = {'a':1}
for k, v in d:
print(k, v)Match it to what it doesd = {'x':1}
d['x'] += 1
del d['x']
print(d['x'])Match it to what it doesfor k, v in d.items():
print(k, v)Match it to what it doesif 'name' in d:
print(d['name'])Match it to what it doesd = {'a':1,'b':2}
for k in d:
print(k)Match it to what it doesd = {'x':10}
for k,v in d.items():
print(k,v)Match it to what it doesFill in the blanks
for key __ d: print(key)for val in d.______(): print(val)for k, v in d._____(): print(k, v)if 'name' __ d: print('Found')for key in d: print(d[___])
Spot the error
Question 1
Ad = {'a': 1, 'b': 2}Bfor k, v in d:C print(k, v)Dprint('Done')
Question 2
Ad = {'a': 1, 'b': 2}Bfor val in d:C print(val)D# expects values
Question 3
Ad = {'a': 1, 'b': 2}Bfor k, v in d.keys():C print(k, v)Dprint('Done')
Question 4
Ad = {'a': 1, 'b': 2}Bfor k in d.items():C print(k)Dprint('Done')
Question 5
Afound = 'Alice' in {'name': 'Alice', 'age': 12}Bd = {'name': 'Alice', 'age': 12}Cprint('Found:', found)D# expects True
