โ† Back

Home โ€บ Output practice โ€บ get() versus brackets

Predict the output: get() versus brackets

๐Ÿ”ฎ Predict the outputTopic: dictionariesDifficulty: easyNo login needed

The snippet

Both lines ask for the same missing key and get completely different treatment. Which one you write decides whether the program crashes or keeps going.

prices = {"pen": 10}
print(prices.get("cap"))
print(prices.get("cap", 0))
print(len(prices))

Your prediction

Type exactly what this program prints โ€” one line per print() call:

The output

None
0
1

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. prices = {"pen": 10}
    One key. "cap" is not in it.
  2. print(prices.get("cap"))
    get returns its default when the key is absent โ€” and the default default is None โ†’ prints None. No exception.
  3. print(prices.get("cap", 0))
    The second argument is the fallback โ†’ 0.
  4. print(len(prices))
    get never inserts anything, so the dict still has one key โ†’ 1. This is the part exams test.

The rule you can reuse

d[k] raises KeyError when k is missing; d.get(k) returns None; d.get(k, fallback) returns the fallback. d.setdefault(k, v) *does* insert v and returns it.

Why most predictions break here

Claiming the dictionary becomes {"pen": 10, "cap": 0}. A lookup with a default does not write. Use setdefault or d[k] = fallback if you want the entry created.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
d = {"a": 1}
d.setdefault("b", 2)
print(d)
print(len(d), d.pop("a"))

Output
{'a': 1, 'b': 2}
2 1

setdefault inserts, so the dict grows to two keys; pop hands back 1 โ†’ {'a': 1, 'b': 2} then 2 1.

Predict this too
d = {"a": 1}
print(d["b"])

Output
KeyError: 'b'

Brackets on a missing key stop the program with KeyError: 'b' โ€” that traceback is the output.

Share your result

Challenge a friend โ€” the link contains the question, never the answer:

Copied โœ“

Keep practising this rule

More output questions โ†’ All interactive problems

Questions this page answers

Is get() slower than brackets?

Marginally, and it never matters in student code. Prefer get (or in) when absence is a normal case, and brackets when a missing key genuinely means a bug you want to crash on.

What is the idiomatic count pattern?

counts[key] = counts.get(key, 0) + 1, or collections.Counter / defaultdict(int) so the zero is created for you.