Concepts / Modifying Dictionary Values

Modifying Dictionary Values

Dictionary lookups use keys, not integer indices: dictionary[key] retrieves the value associated with that key.

  • Programming
Interactive lab

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

  1. A dict maps unique keys to values; the pairs are kept in the order the keys were first inserted (Python 3.7+).
  2. d[k] returns the value for k or raises KeyError: 'k'; d.get(k) returns None and d.get(k, default) the default instead.
  3. k in d tests the keys only; testing a value needs v in d.values(); len(d) counts pairs.
  4. 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.
  5. del d[k] and d.pop(k) remove a pair (KeyError if missing; pop returns the value, or the default if one is given).
  6. 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.

Educational simulation

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.

List0first itemDictionarytwokeydosvalueinteger positionnamed keyretrieves
How does dictionary[key] retrieve a value, and how is that different from accessing a list with an integer index?

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.

Code walkthrough
eng2sp = {"one": "uno", "two": "dos", "three": "tres"}
word = eng2sp["two"]
print(word)
  1. 1
    Python looks for the key "two" in eng2sp.
  2. 2
    That key is paired with the value "dos".
  3. 3
    The 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.
Output
dos

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.

key "two"hash tabletable locationassociated entryvalue "dos"lookup inputlocatesreturns
How does a dictionary use a key to locate its associated value?

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.

python
Output
KeyError: 'four'
eng2sp["four"]key existsassociated valueKeyErrormissing keychecksyesno
What control-flow path occurs when a lookup uses a key that is not present?
Best practice

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.

Code walkthrough
eng2sp = {"one": "uno", "two": "dos", "three": "tres"}
print("one" in eng2sp)
print("uno" in eng2sp)
print("uno" in list(eng2sp.values()))
  1. 1
    The first expression applies in directly to the dictionary, so Python checks its keys and finds "one".
  2. 2
    The second expression also checks keys, but "uno" is not a key.
  3. 3
    The 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".
Output
True
False
True
eng2sp"one"keyTruekey membership"uno"valueTruevalue membershipdirect in checkfound as keyvalues() then list()found as value
How does Python distinguish between checking whether a key exists and checking whether a value appears?

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.

python
Output
3

Dictionaries 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.

OperationWhat Python checksSearch approach
item in a listList itemsLinear search, one item at a time
key in a dictionaryDictionary keysHash-table lookup
value in list(dictionary.values())Extracted dictionary valuesList 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 like

    Using a position-based mental model instead of supplying the dictionary key that identifies the desired value.

    Why it fails

    Dictionary retrieval is driven by keys, not by integer positions.

    Do this instead

    Use dictionary[key] with the key associated with the value you want.

  • Common mistake

    Assuming that a missing key returns None.

    What it looks like

    Looking up eng2sp["four"] when "four" is not stored.

    Why it fails

    A direct lookup of a missing key raises KeyError and can halt execution unless handled.

    Do this instead

    Check 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 like

    Testing "uno" in eng2sp when "uno" is stored as a value.

    Why it fails

    The in operator applied directly to a dictionary checks keys only.

    Do this instead

    Use "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 like

    Expecting a dictionary with three pairs to have a length of six.

    Why it fails

    len() returns the number of key-value pairs.

    Do this instead

    Count each stored pair as one dictionary entry.

Practice the Distinction

EASY

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.
Worked example

Reading the Dictionary State

Determine the results of the five expressions using eng2sp = {"one": "uno", "two": "dos", "three": "tres"}.

  1. 1
    Key lookup

    "two" is a key, so "two" in eng2sp evaluates to True.

  2. 2
    Direct membership test

    "dos" is a value rather than a key, so "dos" in eng2sp evaluates to False.

  3. 3
    Value membership test

    list(eng2sp.values()) contains the values, including "dos", so the third expression evaluates to True.

  4. 4
    Entry count

    The dictionary stores three key-value pairs, so len(eng2sp) evaluates to 3.

  5. 5
    Absent key

    "four" is not present as a key, so eng2sp["four"] raises KeyError.

Result

True, False, True, 3, and KeyError respectively.

Key Takeaways

  1. 1
    Dictionary lookups use keys rather than integer positions: dictionary[key] returns the value paired with key.
  2. 2
    Looking up a missing key raises KeyError unless the situation is handled defensively.
  3. 3
    The in operator checks dictionary keys; searching values requires values() followed by a list membership test.
  4. 4
    len(dictionary) counts key-value pairs.
  5. 5
    Hash 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 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.

Related concepts

More concepts starting with M