Dictionary Basics: Keys, Values, and Methods
The .items() method returns tuples of (key, value) pairs from a dictionary.
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…
Why Both Parts Matter
A dictionary stores relationships between keys and values. When a loop needs only the keys, a basic dictionary loop is enough. When the loop must use each key together with its associated value, use the .items() method. It returns key-value pairs as tuples, allowing the loop to receive both parts at once.
From Items to Variables
Calling d.items() produces key-value tuples. For a dictionary containing three entries, the result can be understood as three pairs, such as ('a', 10), ('b', 1), and ('c', 22). In a loop written as for key, val in d.items():, Python automatically unpacks one tuple during each iteration. The first part goes into key, and the second part goes into val. The variable names are chosen by the programmer; what matters is that the two loop variables receive the tuple's two parts.
d = {'a': 10, 'b': 1, 'c': 22}
for key, val in d.items():
print(val, key)- 1On the first iteration, the tuple ('a', 10) is unpacked, so key is 'a' and val is 10.
- 2On the second iteration, the tuple ('b', 1) is unpacked, so key is 'b' and val is 1.
- 3On the third iteration, the tuple ('c', 22) is unpacked, so key is 'c' and val is 22.
- The dictionary contains three key-value pairs.
d.items()supplies one key-value tuple per iteration.- key and val receive the tuple's two parts.
- The print statement displays the value first and the key second.
Choosing an Iteration Method
Python dictionaries provide three main iteration methods. Use .keys() when the loop needs only keys, .values() when it needs only values, and .items() when it needs both keys and values. Choosing the method that matches the information required by the loop makes the code clearer and avoids trying to obtain information that the loop did not request.
| Method | Information supplied during iteration | Use it when |
|---|---|---|
| .keys() | Keys | Only the dictionary keys are needed |
| .values() | Values | Only the dictionary values are needed |
| .items() | Key-value tuples | Both the key and its value are needed |
The three main dictionary iteration choices
Tracing Every Loop
What do you think happens?
What will this loop print, and in what order?
Reveal answer
10 a, then 1 b, then 22 c
Each item is unpacked as key and val. The print statement places val first and key second.
10 a
1 b
22 cThe most reliable way to predict this output is to separate the task into two questions for each tuple: which value is assigned to key, and which value is assigned to val? Then inspect the print statement to determine the display order. For ('a', 10), key receives 'a' and val receives 10, but print(val, key) displays 10 first. Repeating that process for the other two tuples gives the complete output.
Mistakes with Dictionary Loops
Common mistake Expecting a basic dictionary loop to provide both parts of each entry
What it looks likefor item in d:Why it failsA basic dictionary loop gives the loop variable only the keys.
Do this insteadUse for key, val in d.items(): when the loop needs both the key and its corresponding value.
Common mistake Using .keys() when the value is also needed
What it looks likefor key in d.keys():Why it failsThe iteration method supplies keys only, so the loop does not receive each key-value pair together.
Do this insteadUse .items() and unpack each pair into two variables.
Common mistake Assuming the print order is determined by the tuple order
What it looks likefor key, val in d.items(): print(val, key)Why it failsThe tuple contains the key first and value second, but the print statement deliberately displays val before key.
Do this insteadTrace the assignments first, then read the print arguments from left to right.
Common mistake Treating .values() as if it supplied keys and values
What it looks likefor key, val in d.values():Why it failsThe .values() method is for iterating through values only, not key-value tuples.
Do this insteadChoose .items() when both parts are required.
Choose the iteration method based on the loop's actual need: .keys() for keys, .values() for values, and .items() for both. When using .items(), name the two loop variables so their roles are clear, such as key and val. For output prediction, trace one tuple at a time instead of trying to read the entire loop at once.
Practice the Trace
Given d = {'x': 5, 'y': 8}, identify the values of key and val on each iteration of this loop, then write the two output lines: for key, val in d.items(): print(key, val)
Hints
- Treat each dictionary entry as one key-value tuple.
- The first loop variable receives the key and the second loop variable receives the value.
- Read
print(key, val)from left to right.
Tracing an items() loop
Predict the output of for key, val in d.items(): print(key, val) when d is {'x': 5, 'y': 8}.
- 1First tuple
The first pair is ('x', 5), so key receives 'x' and val receives 5. The line prints x 5.
- 2Second tuple
The second pair is ('y', 8), so key receives 'y' and val receives 8. The line prints y 8.
The output is x 5 followed by y 8.
Key Takeaways
- 1The .items() method returns key-value pairs as tuples.
- 2In for key, val in
d.items():, each tuple is automatically unpacked into key and val. - 3Use .keys() for keys only, .values() for values only, and .items() for both.
- 4To predict output, trace each tuple, record the variables it assigns, and then follow the print statement's argument order.
At a glance
- Use .items() when a loop needs both each dictionary key and its associated value.
- Each item is a tuple, and tuple unpacking places its first part in the first loop variable and its second part in the second loop variable.
- Use .keys(), .values(), or .items() according to the information the loop needs.
- Predict dictionary-loop output by tracing one key-value tuple at a time and checking the order used by print.