Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.items() method

Reference for Python dict.items(): loop over key-value pairs, live view behavior, set-like operations, sorting by value and the error from changing size mid-loop.

The dict.items() method returns a view of a dictionary's key-value pairs. Each element is a two-item tuple (key, value). It is the standard way to loop over both keys and values at once.

The result is a view, not a list. It does not copy the data, and it stays connected to the dictionary: if the dictionary changes, the view shows the change. Use list(d.items()) when you need a snapshot.

Python
ages = {"Ada": 36, "Linus": 28}
for name, age in ages.items():
    print(name, age)

Try it

Python Looping over pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Live views and safe edits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
dict.items()

items() takes no arguments.

Return value: a dict_items view object. It supports len(), iteration, membership tests and reversed() (Python 3.8+).

Raises: nothing when called. A RuntimeError is raised if the dictionary changes size while you iterate over the view.

Usage notes

  • Order is insertion order (guaranteed since Python 3.7). The iteration order of a view matches the dictionary.
  • Views are live. Adding, removing or changing entries is reflected immediately. They are cheap to create, and no data is copied.
  • Do not add or delete keys while iterating. That raises RuntimeError. Iterate over list(d.items()) for a safe snapshot. Changing the value of an existing key during iteration is allowed.
  • Set-like operations. Because the pairs are hashable when the values are, items() supports &, |, - and ^, which compare whole pairs. If a value is unhashable (such as a list), some set operations raise TypeError.
  • Membership checks pairs. (k, v) in d.items() is true only when both match.
  • Unpack in the loop header (for k, v in d.items()), which reads better than indexing a tuple.
  • Sorting. sorted(d.items()) sorts by key, then value; give key= to sort by value. The result is a list of tuples, which dict() turns back into a dictionary.
  • Looping with for k in d gives keys only, and then d[k] does an extra lookup. items() avoids that.