Dictionaries – Methods (keys, values, items, get), online

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

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

Discover other journeys with this module

What students will learn in this module

Every question in Module 38

Quick questions

  1. What does .keys() return?AAll the keysBAll the values
  2. What does .values() return?AAll the valuesBAll the keys
  3. What does .items() return?AKey-value pairs as tuplesBJust keys
  4. d.get('x', 0) what happens if 'x' doesn't exist?AKeyErrorBReturns 0 (the default)
  5. 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 does
d = {'x': 5}
d.pop('y')
Match it to what it does
d.get('missing', 0)Match it to what it does
for k, v in d.items():
    print(k, v)
Match it to what it does
d = {'a':1,'b':2}
print(list(d.keys()))
Match it to what it does
d = {'a':1}
print(d.get('b', 99))
Match it to what it does

Fill in the blanks

  1. d = {'a': 1, 'b': 2}
    print(d.____(  ))
  2. d = {'a': 1, 'b': 2}
    print(d.______(  ))
  3. d = {'a': 1}
    print(d.___('b', 0))
  4. d = {'x': 10}
    val = d.___('x')
  5. 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')