Modifying Dictionary Values
Dictionary lookups use keys, not integer indices: dictionary[key] retrieves the value associated with that key.
From Positions to Keys
When you first work with dictionaries after using lists, it is natural to expect the same access pattern. A list gives you an item by its position, such as index 0 or index 1. A dictionary does not use positional indexing for retrieval. Instead, you provide a key, and Python returns the value paired with that key.
Tracing a Key Lookup
Square brackets appear in both list access and dictionary access, but the meaning inside the brackets changes. With a dictionary, the expression dictionary[key] asks Python to find that specific key and return its associated value. The key determines the lookup; the dictionary item's position does not.
eng2sp = {"one": "uno", "two": "dos", "three": "tres"} word = eng2sp["two"] print(word)
The important state change is not a movement to a numbered position. The key "two" identifies a stable mapping to "dos". Adding other key-value pairs around it does not change which value the key selects.
Missing Keys and KeyError
A key lookup succeeds only when the requested key exists. If the key is absent, Python raises a KeyError exception. This is not the same as receiving None, and it is not a silent unsuccessful lookup. Unless the exception is explicitly handled, it halts execution.
KeyError: 'four'Before a direct lookup, verify that the key exists when a missing key is a normal possibility. The source also identifies defensive methods such as get() as an approach for avoiding KeyError when appropriate. The important design choice is to avoid treating a missing key as though it were an ordinary value.
Membership Checks
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 word can appear inside the dictionary and still produce False if it appears only as a value.
eng2sp = {"one": "uno", "two": "dos", "three": "tres"} print("one" in eng2sp) print("uno" in eng2sp) print("uno" in list(eng2sp.values()))
Counting Entries and Lookup Speed
Calling len() on a dictionary returns the total number of key-value pairs stored in it. It does not count only keys or only values as separate collections; each stored pair contributes one entry to the count.
3Dictionaries and lists also differ in how membership searches work. A list uses a linear search that checks items one by one. As the list grows, the search can take proportionally longer. A dictionary uses a hash-table algorithm: a mathematical function transforms a key into a location associated with its value. This enables key membership tests in constant time, approximately regardless of dictionary size.
| Operation | What Python checks | Search approach |
|---|---|---|
| item in a list | List items | Linear search, one item at a time |
| key in a dictionary | Dictionary keys | Hash-table lookup |
| value in list(dictionary.values()) | Extracted dictionary values | List search through the extracted values |
Common Lookup Mistakes
Treating a dictionary like a list by using an integer position as though it were an index.
Dictionary retrieval is driven by keys, not by integer positions.
Fix:
Use dictionary[key] with the key associated with the value you want.Assuming that a missing key returns None.
A direct lookup of a missing key raises KeyError and can halt execution unless handled.
Fix:
Check for key membership or use a defensive method such as get() when appropriate.Using a direct dictionary membership test to search values.
The in operator applied directly to a dictionary checks keys only.
Fix:
Use "uno" in list(eng2sp.values()) when the goal is to search values.Interpreting len(dictionary) as a count of all keys and values separately.
len() returns the number of key-value pairs.
Fix:
Count each stored pair as one dictionary entry.
Practice the Distinction
Given the dictionary below, decide what each expression checks and predict its result before running it. eng2sp = {"one": "uno", "two": "dos", "three": "tres"} 1. "two" in eng2sp 2. "dos" in eng2sp 3. "dos" in list(eng2sp.values()) 4. len(eng2sp) 5. What happens with eng2sp["four"]?
Hints
- A direct in check on a dictionary examines keys.
- Use values() followed by list() to search for a value.
- len() counts key-value pairs.
- A direct lookup of an absent key raises KeyError.
Reading the Dictionary State
Determine the results of the five expressions using eng2sp = {"one": "uno", "two": "dos", "three": "tres"}.
Key lookup: "two" is a key, so "two" in eng2sp evaluates to True.
Direct membership test: "dos" is a value rather than a key, so "dos" in eng2sp evaluates to False.
Value membership test: list(eng2sp.values()) contains the values, including "dos", so the third expression evaluates to True.
Entry count: The dictionary stores three key-value pairs, so len(eng2sp) evaluates to 3.
Absent key: "four" is not present as a key, so eng2sp["four"] raises KeyError.
True, False, True, 3, and KeyError respectively.
Key Takeaways
- Dictionary lookups use keys rather than integer positions: dictionary[key] returns the value paired with key.
- Looking up a missing key raises KeyError unless the situation is handled defensively.
- The in operator checks dictionary keys; searching values requires values() followed by a list membership test.
- len(dictionary) counts key-value pairs.
- Hash tables allow dictionary key membership tests and lookups to operate in constant time, unlike linear list searches.
Key Takeaways
- Use a dictionary key to retrieve its associated value; dictionary access is not positional list indexing.
- Expect KeyError when a direct lookup uses a missing key.
- Remember that in checks keys on a dictionary, while value searches require dictionary.values() and a list membership test.
- Use len() to count key-value pairs, and recognize that hash tables support fast key lookups.