Dictionaries – Iteration, online

Six activities your students do on their own devices. See who's finished, and their scores.

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.

Discover other journeys with this module

What students will learn in this module

Every question in Module 39

Quick questions

  1. for key in d: what does key get?AEach key, one at a timeBEach value
  2. How do you loop through values?Afor v in d.values():Bfor v in d:
  3. How do you loop through keys AND values?Afor k, v in d.items():Bfor k, v in d:
  4. d = {'a':1, 'b':2}\nfor k in d:\n print(k)\nWhat prints?A1 then 2Ba then b
  5. 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 does
d = {'x':1}
d['x'] += 1
del d['x']
print(d['x'])
Match it to what it does
for k, v in d.items():
    print(k, v)
Match it to what it does
if 'name' in d:
    print(d['name'])
Match it to what it does
d = {'a':1,'b':2}
for k in d:
    print(k)
Match it to what it does
d = {'x':10}
for k,v in d.items():
    print(k,v)
Match it to what it does

Fill in the blanks

  1. for key __ d:
        print(key)
  2. for val in d.______():
        print(val)
  3. for k, v in d._____():
        print(k, v)
  4. if 'name' __ d:
        print('Found')
  5. 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