Modifying Dictionary Values
Dictionary lookups use keys, not integer indices: dictionary[key] retrieves the value associated with that key.
Try it: Dictionary Operations
How a Python dict behaves under everyday operations: d[k] raises KeyError for a missing key while get() returns None or a default, in tests keys (not values), assignment adds a new key at the end but updates an existing key in place, del and pop remove pairs, and iteration, keys(), values() and items() follow insertion order — with keys() a live view and list(d.keys()) a frozen copy.
How it works
- A dict maps unique keys to values; the pairs are kept in the order the keys were first inserted (Python 3.7+).
- d[k] returns the value for k or raises KeyError: 'k'; d.get(k) returns None and d.get(k, default) the default instead.
- k in d tests the keys only; testing a value needs v in d.values(); len(d) counts pairs.
- d[k] = v adds a new pair at the end when k is new, and replaces the value in place (same position) when k already exists; update() does this for each pair.
- del d[k] and d.pop(k) remove a pair (KeyError if missing; pop returns the value, or the default if one is given).
- keys(), values() and items() are views of the current dict; list(d.keys()) copies the keys at that moment. Filtering builds a NEW dict of the pairs that pass a test.
Default run (3 steps): d = {'apple': 3, 'fig': 7, 'pear': 5} — 3 key-value pairs, kept in insertion order. Choose an operation. Example: d.get('kiwi', 0). … The key is missing, so get returns the default 0 instead of raising KeyError. d is not changed.
Simplified: String keys (short lowercase words) and small int values, at most 8 pairs. The lab models what the operations do, not how CPython stores the dict (see the hashing lab for that). Every operation's result, error text, printed output and view contents match CPython 3.12 on 150 random operation sequences.
Loading the simulation…
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)- 1Python looks for the key "two" in eng2sp.
- 2That key is paired with the value "dos".
- 3The lookup produces "dos", regardless of where the pair appears among the other entries.
- The dictionary contains keys such as "one" and "two".
- The key "two" selects its paired value.
- The retrieved value is assigned to word and printed.
dosThe 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()))- 1The first expression applies in directly to the dictionary, so Python checks its keys and finds "one".
- 2The second expression also checks keys, but "uno" is not a key.
- 3The third expression converts the dictionary values to a list and checks that list, where "uno" appears.
- "one" is a key.
- "uno" is a value, not a key.
- The values are extracted before checking for "uno".
True
False
TrueCounting 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 |
The container and expression determine what is searched.
Common Lookup Mistakes
Common mistake Treating a dictionary like a list by using an integer position as though it were an index.
What it looks likeUsing a position-based mental model instead of supplying the dictionary key that identifies the desired value.
Why it failsDictionary retrieval is driven by keys, not by integer positions.
Do this insteadUse dictionary[key] with the key associated with the value you want.
Common mistake Assuming that a missing key returns None.
What it looks likeLooking up eng2sp["four"] when "four" is not stored.
Why it failsA direct lookup of a missing key raises
KeyErrorand can halt execution unless handled.Do this insteadCheck for key membership or use a defensive method such as get() when appropriate.
Common mistake Using a direct dictionary membership test to search values.
What it looks likeTesting "uno" in eng2sp when "uno" is stored as a value.
Why it failsThe in operator applied directly to a dictionary checks keys only.
Do this insteadUse "uno" in list(eng2sp.values()) when the goal is to search values.
Common mistake Interpreting len(dictionary) as a count of all keys and values separately.
What it looks likeExpecting a dictionary with three pairs to have a length of six.
Why it failslen()returns the number of key-value pairs.Do this insteadCount 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"}
- "two" in eng2sp
- "dos" in eng2sp
- "dos" in
list(eng2sp.values()) len(eng2sp)- What happens with eng2sp["four"]?
Hints
- A direct in check on a dictionary examines keys.
- Use
values()followed bylist()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"}.
- 1Key lookup
"two" is a key, so "two" in eng2sp evaluates to True.
- 2Direct membership test
"dos" is a value rather than a key, so "dos" in eng2sp evaluates to False.
- 3Value membership test
list(eng2sp.values())contains the values, including "dos", so the third expression evaluates to True. - 4Entry count
The dictionary stores three key-value pairs, so
len(eng2sp)evaluates to 3. - 5Absent key
"four" is not present as a key, so eng2sp["four"] raises
KeyError.
True, False, True, 3, and KeyError respectively.
Key Takeaways
- 1Dictionary lookups use keys rather than integer positions: dictionary[key] returns the value paired with key.
- 2Looking up a missing key raises
KeyErrorunless the situation is handled defensively. - 3The in operator checks dictionary keys; searching values requires
values()followed by a list membership test. - 4
len(dictionary)counts key-value pairs. - 5Hash tables allow dictionary key membership tests and lookups to operate in constant time, unlike linear list searches.
At a glance
- Use a dictionary key to retrieve its associated value; dictionary access is not positional list indexing.
- Expect
KeyErrorwhen 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.