Looking Up a Key in a Dictionary
A dictionary connects each distinct key to a value. A lookup needs a policy for a key that has no entry.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace one missing lookup
A dictionary holding {"tea": 4} returns four for tea. Red tea may be a different key under exact text equality. The property of hashable keys lets dictionaries store these names, and canonicalization determines whether alternate spellings should match.
Choose the error channel
Python bracket lookup raises on a missing key. The get method may return a default. If the dictionary may store that same default explicitly, use a unique missing sentinel or check membership before reading.[1]
Distinguish a missing key from a stored empty value
A directory can contain {"A8": "", "B3": "north"}. Looking up A8 with a default empty string returns the same result as looking up absent key C2 with that default, even though the directory contains A8. Check key membership when presence has meaning or use a sentinel beyond the set of valid values. If missing data indicates a broken reference, indexed lookup's exception can make the distinction explicit. See missing values and sentinels.
Check the key type at the boundary
The integer key 12 and the string key "12" are distinct in an ordinary Python dictionary. A lookup from form text needs the same conversion policy used when inserting keys. Leading zeros may be meaningful for textual identifiers. Converting "012" to twelve would merge them under a numeric policy. Test a present empty value, an absent key and two visibly similar keys. See stable identifiers.