Dictionaries – Methods (keys, values, items, get), online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
Dictionaries – Methods (keys, values, items, get) in one minute
What students need to know
.get(key, default) is safe — returns the default instead of raising a KeyError. .items() returns (key, value) tuples — great for iterating with unpacking.
.keys() gives the left side of each pair — the lookup labels. The second argument to .get() is the fallback when the key is missing.
Mistakes students make
- It's keys() with an 's': not key().
- It's values() with an 's': not value().
- It's items() with an 's': not item().
- Use parentheses () to call methods, not square brackets [].
PREVIOUS · MODULE 37Dictionaries – Basics (creation, accessing)
YOU ARE HERE · MODULE 38Dictionaries – Methods (keys, values, items, get)
NEXT · MODULE 39Dictionaries – Iteration
What students will learn in this module
Every question in Module 38
Quick questions
- What does .keys() return?AAll the keysBAll the values
- What does .values() return?AAll the valuesBAll the keys
- What does .items() return?AKey-value pairs as tuplesBJust keys
- d.get('x', 0) what happens if 'x' doesn't exist?AKeyErrorBReturns 0 (the default)
- d.get('x') what if 'x' doesn't exist and no default?AKeyErrorBReturns None
Key terms
Students type the meaning of:
.keys().values().items().get(key, default)
Match the pairs
d = {'a': 1}
d.get('b')
print(d['b'])Match it to what it doesd = {'x': 5}
d.pop('y')Match it to what it doesd.get('missing', 0)Match it to what it doesfor k, v in d.items():
print(k, v)Match it to what it doesd = {'a':1,'b':2}
print(list(d.keys()))Match it to what it doesd = {'a':1}
print(d.get('b', 99))Match it to what it doesFill in the blanks
d = {'a': 1, 'b': 2} print(d.____( ))d = {'a': 1, 'b': 2} print(d.______( ))d = {'a': 1} print(d.___('b', 0))d = {'x': 10} val = d.___('x')d = {'a': 1} d.______({'b': 2})
Spot the error
Question 1
Ad = {'a': 1, 'b': 2}Ball_keys = d.key()Cprint('Keys:', all_keys)Dprint('Done')
Question 2
Ad = {'a': 1, 'b': 2}Ball_vals = d.value()Cprint('Values:', all_vals)Dprint('Done')
Question 3
Ad = {'a': 1, 'b': 2}Ball_items = d.item()Cprint('Items:', all_items)Dprint('Done')
Question 4
Ad = {'a': 1, 'b': 2}Bval = d.get['b']Cprint('Value:', val)Dprint('Done')
Question 5
Aresult = {'a': 1, 'b': 2}.pop()Blabel = 'Dict'Cprint('Result:', result)Dprint('Done')
