KKAIROS
Practical guideIllustrative3 min read

Python dictionaries: lookup, default values and the KeyError

A dictionary maps keys to values; d[key] raises KeyError when the key is missing, while get returns a default instead.

Published:

Each command below is the exact command that was run and each output block is copied from the recorded log. Test ids, log hashes and exit statuses are in the evidence table.

TE-29-A: a missing key raises KeyError; get returns a default instead

Setup for this run, inside a throwaway directory (mktemp -d):

printf 'd = {"a": 1}\nprint(d["b"])\n' > s.py

Command:

python3 s.py 2>&1 | tail -1; echo exit=${PIPESTATUS[0]}; python3 -c "d={'a':1}; print(d.get('b','missing'))"

Recorded output:

KeyError: 'b'
exit=1
missing

This run checks the exit status and records the output; it asserts no expected text.

TE-29-B: assigning to a new key adds it, and del removes a key

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

python3 -c "d={'a':1}; d['b']=2; del d['a']; print(d, len(d))"

Recorded output:

{'b': 2} 1

Exit status: 0. This status and the output match what was written before the run.

TE-29-C: expected non-zero exit: del on a key that is not in the dict raises KeyError

No setup needed: the command below creates what it uses in the throwaway folder.

Command:

python3 -c "d={}; del d['x']"

Recorded output: none, standard output was empty.

Standard error from the same run:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
KeyError: 'x'

Exit status: 1. This status and the output match what was written before the run.

TE-29-B: the dict started as {'a': 1}. After d['b']=2 and del d['a'] it printed {'b': 2} and length 1. TE-29-C: del d['x'] on an empty dict exited with status 1. The last line of standard error is KeyError: 'x'.

Limits

Insertion order is preserved in current Python; not a promise about older versions.

Ad

Source

Evidence

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-29-A | a missing key raises KeyError; get returns a default instead | 0 | PASS | 374468456186 | | TE-29-B | assigning to a new key adds it, and del removes a key | 0 | PASS | b2eb070762fc | | TE-29-C | expected non-zero exit: del on a key that is not in the dict raises KeyError | 1 | PASS | 5b2a226e2baf |

Every row has a recorded log holding the setup commands, the command, stdout, stderr, exit status and the final directory state. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides