Dictionary Methods: get(), keys(), and values()
Dictionary lookups use keys, not integer indices: dictionary[key] retrieves the value associated with that key.
From Positions to Keys
Lists teach us to retrieve items by position: index 0, index 1, and so on. Dictionaries use a different idea. A dictionary does not use integer positions as its retrieval mechanism. Instead, you provide a key and receive the value associated with that key. The square brackets look familiar, but dictionary[key] means key-based lookup, not positional indexing.
A dictionary mapping is stable by key: the key two maps to the value dos regardless of where that pair appears relative to other dictionary items.
Tracing a Successful Lookup
dosThe lookup supplies the key two, so Python searches for that key and returns its paired value, dos. The lookup does not ask for the second item by position. It asks for the item whose key is exactly two.
What do you think happens?
What happens when the requested key is not present?
Reveal answer
Answer: Python raises a KeyError.
A bracket lookup for a missing key is an exception-producing operation. It is not a silent failure and it does not automatically return None.
Handling Missing Keys
A bracket lookup requires the requested key to exist. If it does not, Python raises a KeyError and execution halts unless the exception is explicitly handled. This behavior gives you a clear signal that the requested mapping was not found, but it can be inconvenient when a missing key is an expected possibility.
The get() method is one of the defensive methods identified for situations where you want to avoid a KeyError. The important decision is whether a missing key should be treated as an exceptional failure or as an ordinary case that your program can handle. Use bracket lookup when the key is required and use a defensive approach such as get() when absence is acceptable.
| Operation | What it uses | When the key exists | When the key is missing |
|---|---|---|---|
| dictionary[key] | A key | Returns the associated value | Raises KeyError |
| dictionary.get(key) | A key | Defensive key-based retrieval | Provides a path that avoids the bracket-lookup exception |
Keys, Values, and Membership
The in operator has a specific meaning when it is applied directly to a dictionary: it checks keys. It does not search the dictionary's values. Therefore, a string can appear as a value and still produce False when tested directly against the dictionary.
True
False
TrueThe first test is True because one is a key. The second is False because uno is a value, not a key. To check for a value, call values(), convert the resulting values to a list, and apply in to that list. The two-step form is necessary because direct dictionary membership is optimized for key lookup.
Views and Dictionary Size
The keys() method exposes the dictionary's keys, while the values() method exposes its values. These methods help you inspect the two sides of the dictionary's key-value mappings. When you need to search for a value, values() supplies the collection that you can convert to a list before applying in.
The len() function counts the total number of key-value pairs stored in a dictionary. It does not count only the keys or only the values as separate collections. Each mapping from one key to one value contributes one item to the dictionary's length.
3
['one', 'two', 'three']
['uno', 'dos', 'tres']For a dictionary with three key-value pairs, len() returns 3. The keys() and values() results correspond to the dictionary's two collections of mapping participants: keys on one side and values on the other.
Why Key Searches Stay Fast
A list membership test uses a linear search. Python checks items one by one from the beginning until it finds a match or reaches the end. As the list grows, the amount of searching can grow proportionally; in the worst case, a list with 1,000 items requires checking roughly 1,000 times as many positions as a list with 1 item.
Dictionaries use a hash-table algorithm instead. A mathematical function transforms a key into a memory location where the associated value is stored. Because the transformation is performed in constant time, dictionary key lookup takes approximately the same amount of time whether the dictionary contains 10 items or 10 million items. This is why dictionaries are useful for fast retrieval and membership testing.
Mistakes Beginners Make
Treating a dictionary like a list by using an integer as though it were a position.
Dictionary retrieval is driven by keys, not integer positions.
Fix:
Use the actual key, such as eng2sp["one"], when the key exists.Assuming a missing bracket lookup returns None or an empty result.
A missing key raises KeyError.
Fix:
Check key existence first or use a defensive method such as get() when missing keys are acceptable.Using direct dictionary membership to search values.
The in operator checks keys when applied directly to a dictionary.
Fix:
Use list(eng2sp.values()) and then apply in to that list.Interpreting len(dictionary) as the number of individual pieces across both collections.
len() counts key-value pairs.
Fix:
Read the result as the number of mappings stored in the dictionary.
Practice the Distinctions
Reading a small translation dictionary
Given eng2sp = {"one": "uno", "two": "dos"}, identify which expressions perform key lookup, which test key membership, which test value membership, and what len(eng2sp) counts.
Key lookup: eng2sp["two"] retrieves the value paired with the key two, which is dos.
Key membership: "one" in eng2sp checks for the key one and evaluates to True.
Value membership: "uno" in eng2sp checks keys rather than values and therefore evaluates to False. To search values, use "uno" in list(eng2sp.values()).
Dictionary length: len(eng2sp) counts the two key-value pairs stored in the dictionary.
Dictionary lookup uses two, direct membership checks one as a key, value membership requires values(), and len() reports two mappings.
For a dictionary with the mappings "red": "rojo" and "blue": "azul", decide what each operation is intended to check: retrieving the value for "blue", checking whether "rojo" is a key, checking whether "rojo" is a value, and counting the stored mappings.
Hints
- Ask whether each operation is using a key directly or searching the values collection.
- Remember that direct in checks keys only.
- Remember that len() counts key-value pairs.
Key Takeaways
- Dictionary lookups use keys rather than integer positions.
- A missing key in bracket lookup raises KeyError; get() is a defensive method for appropriate missing-key situations.
- The in operator checks dictionary keys directly, while value membership requires values() and a separate membership test.
- len(dictionary) counts key-value pairs.
- Hash tables transform keys into memory locations, making dictionary key lookup usually fast.
Key Takeaways
- Dictionaries retrieve values through keys, not integer indices.
- Bracket lookup raises KeyError for a missing key, while get() offers a defensive alternative when absence is acceptable.
- Direct dictionary membership checks keys; checking values requires values() and a separate search.
- len() returns the number of key-value pairs.
- Hash-table algorithms make dictionary key lookup and membership testing usually fast.