Concepts / Dictionary Basics: Keys, Values, and Methods

Dictionary Basics: Keys, Values, and Methods

The .items() method returns tuples of (key, value) pairs from a dictionary.

  • 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…

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.items()key-value pairs('a', 10)one tuplekey'a'val10producesfirst partsecond part
How does each key-value tuple from .items() become two separate variables inside a for loop?
Code walkthrough
d = {'a': 10, 'b': 1, 'c': 22}

for key, val in d.items():
    print(val, key)
  1. 1
    On the first iteration, the tuple ('a', 10) is unpacked, so key is 'a' and val is 10.
  2. 2
    On the second iteration, the tuple ('b', 1) is unpacked, so key is 'b' and val is 1.
  3. 3
    On 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.

.keys()keys onlykeyone key.values()values onlyvalueone value.items()key-value tuples(key, value)one tupleproducesproducesproduces
What does each iteration method produce, and which information is available to the loop?
MethodInformation supplied during iterationUse it when
.keys()KeysOnly the dictionary keys are needed
.values()ValuesOnly the dictionary values are needed
.items()Key-value tuplesBoth 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?

  • 10 a, then 1 b, then 22 c

  • a 10, then b 1, then c 22

  • Only the keys a, b, and c

Reveal answer
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.

Iteration 1key='a', val=1010 aprinted outputIteration 2key='b', val=11 bprinted outputIteration 3key='c', val=2222 cprinted outputprintsprintsprints
What value is produced on each loop iteration, and what output appears after all key-value pairs are processed?
Output
10 a
1 b
22 c

The 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 like
    for item in d:
    Why it fails

    A basic dictionary loop gives the loop variable only the keys.

    Do this instead

    Use 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 like
    for key in d.keys():
    Why it fails

    The iteration method supplies keys only, so the loop does not receive each key-value pair together.

    Do this instead

    Use .items() and unpack each pair into two variables.

  • Common mistake

    Assuming the print order is determined by the tuple order

    What it looks like
    for key, val in d.items(): print(val, key)
    Why it fails

    The tuple contains the key first and value second, but the print statement deliberately displays val before key.

    Do this instead

    Trace 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 like
    for key, val in d.values():
    Why it fails

    The .values() method is for iterating through values only, not key-value tuples.

    Do this instead

    Choose .items() when both parts are required.

Best practice

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

EASY

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

Tracing an items() loop

Predict the output of for key, val in d.items(): print(key, val) when d is {'x': 5, 'y': 8}.

  1. 1
    First tuple

    The first pair is ('x', 5), so key receives 'x' and val receives 5. The line prints x 5.

  2. 2
    Second tuple

    The second pair is ('y', 8), so key receives 'y' and val receives 8. The line prints y 8.

Result

The output is x 5 followed by y 8.

Key Takeaways

  1. 1
    The .items() method returns key-value pairs as tuples.
  2. 2
    In for key, val in d.items():, each tuple is automatically unpacked into key and val.
  3. 3
    Use .keys() for keys only, .values() for values only, and .items() for both.
  4. 4
    To 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.

Related concepts

More concepts starting with D