KKAIROS
Practical guideIllustrative3 min read

Python dict.get: read a key without KeyError

d.get(key, default) returns default when the key is missing, and None when you give no default. d[key] raises KeyError for a missing key.

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-95-A: get returns a default or None, and indexing a missing key raises KeyError

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

cat > s.py <<'EOS'
d = {'a': 1}
print(d.get('a'), d.get('b'), d.get('b', 0))
try:
    d['b']
except KeyError:
    print('KeyError')
EOS

Command:

python3 s.py

Recorded output:

1 None 0
KeyError

Exit status: 0. The output matches the expected text written before the run.

TE-95-B: get leaves the dict unchanged, while setdefault inserts the key

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

cat > s.py <<'EOS'
d = {'a': 1}
d.get('b', 0)
print(d)
d.setdefault('b', 0)
print(d)
EOS

Command:

python3 s.py

Recorded output:

{'a': 1}
{'a': 1, 'b': 0}

Exit status: 0. The output matches the expected text written before the run.

TE-95-C: expected non-zero exit: an uncaught d['b'] on a missing key prints KeyError and exits with status 1

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

cat > s.py <<'EOS'
d = {'a': 1}
print(d['b'])
EOS

The file ../err.txt sits one level above the working folder, inside the same throwaway tree. The output block below shows only the last line of the error; the full traceback went to ../err.txt.

Command:

python3 s.py 2>../err.txt; rc=$?; tail -n 1 ../err.txt; exit $rc

Recorded output:

KeyError: 'b'

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

Reading the recorded output

The first printed line holds three values. d.get('a') gave 1, the value stored for the key a. d.get('b') gave None, because b is not in the dict and no default was given. d.get('b', 0) gave 0, the default that was passed in. In the second part, d['b'] on the same dict raised an error, and the except branch printed KeyError. TE-95-A does not print d after these reads, so it does not show whether d held the same items afterwards. TE-95-B does.

TE-95-B: after d.get('b', 0), d still printed {'a': 1}. After d.setdefault('b', 0) it printed {'a': 1, 'b': 0}, so setdefault added the key and get did not. TE-95-C: d['b'] with no try block stopped with KeyError: 'b' and exit status 1.

Ad

Limits

The docs (https://docs.python.org/3/library/stdtypes.html#dict.get) say: If default is not given, it defaults to None, so that this method never raises a KeyError. Only get, indexing and setdefault on a one-key dict were tested.

Source

Evidence table

| Test | What it checks | Exit | Verdict | Log sha256 (first 12) | |---|---|---|---|---| | TE-95-A | get returns a default or None, and indexing a missing key raises KeyError | 0 | PASS | 8e64116b3bce | | TE-95-B | get leaves the dict unchanged, while setdefault inserts the key | 0 | PASS | bf2f1d9f41ec | | TE-95-C | expected non-zero exit: an uncaught d['b'] on a missing key prints KeyError and exits with status 1 | 1 | PASS | 97bf84068f16 |

Recorded on: bash 5.1.16(1)-release; git version 2.34.1; Python 3.10.12. Locale C.UTF-8, TZ=UTC. Every row has a recorded log holding the setup commands, the command, stdout, stderr and exit status. The first 12 characters of the log's sha256 are in the table.

All full guides: All guides