Python dict.popitem() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
dict method

Definition

popitem() removes the pair that was inserted last and returns it as a (key, value) tuple. Since Python 3.7 this LIFO (last in, first out) order is guaranteed.

That makes a dict usable as a stack of named entries, for example an undo history. It takes no arguments, and calling it on an empty dict raises KeyError.

dict.popitem() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as edits.popitem(...). No import is needed.

Syntax

Call it with no arguments and unpack the returned pair if you like.

python
key, value = d.popitem()
pair = d.popitem()
CallWhat it does
{"a": 1, "b": 2}.popitem()Returns ('b', 2), the last inserted pair.
{"only": 0}.popitem()Returns ('only', 0); the dict becomes {}.
{}.popitem()Raises KeyError.

To take a specific key out instead, use pop(); to empty the whole dict at once, use clear().

Method signatures
python
dict.popitem()
# returns: the last inserted (key, value) pair, as a tuple

Parameters

popitem() takes no parameters; you cannot choose which pair it removes.

Return Value

Return ValueDescription
tupleA 2-tuple (key, value) for the most recently inserted key. That pair is no longer in the dict.

Python Examples

Example 1 — Undo the Latest Edits in a Text Editor

Record edits as named steps, then undo them newest first.

python
edits = {}
edits["step1"] = "type 'Hello'"
edits["step2"] = "make bold"
edits["step3"] = "add link"

last = edits.popitem()
print(last)
key, action = edits.popitem()
print("undo", key, "->", action)
print(edits)

How It Works

  1. Newest out first. step3 was inserted last, so the first popitem() returns it as a tuple.
  2. Unpack the pair. key, action = edits.popitem() splits the next pair, step2, into two variables.
  3. One step left. Only step1 remains after two undos.
  4. Quote choice in repr. The value contains single quotes, so Python's repr wraps it in double quotes: "type 'Hello'".

Example 2 — Deliver Every Parcel Until None Are Left

Pop pairs in a while loop, then show what happens when the dict is already empty.

python
parcels = {"P1": "Oslo", "P2": "Lima", "P3": "Cairo"}

while parcels:
    code, city = parcels.popitem()
    print(f"deliver {code} to {city}")

try:
    parcels.popitem()
except KeyError:
    print("popitem() on an empty dict raises KeyError")
print(parcels)

How It Works

  1. Truthiness loop. while parcels: keeps going as long as the dict has at least one pair.
  2. Reverse order. Deliveries run P3, P2, P1: the opposite of the order the parcels were added.
  3. Safe stop. The loop ends exactly when the dict is empty, so it never calls popitem() on nothing.
  4. Empty means KeyError. Calling it once more on {} raises KeyError, caught here.

Example 3 — Track Recently Opened Files

See that updating a value keeps its place, while popping and re-inserting a key makes it the newest entry.

python
recent = {"report.pdf": 1, "notes.txt": 2, "photo.png": 3}

recent["report.pdf"] = 10
print(recent.popitem())

recent["report.pdf"] = recent.pop("report.pdf")
print(list(recent))
print(recent.popitem())
print(recent)

How It Works

  1. Update is not insert. Giving report.pdf a new value leaves it first in line, so popitem() still removes photo.png.
  2. Move to the end. pop() removes report.pdf and the assignment inserts it again, now after notes.txt.
  3. New last pair. The next popitem() returns report.pdf with its updated value 10.
  4. Result. Only notes.txt is left in the dict.

Frequently Asked Questions

The pair that was inserted most recently. Since Python 3.7 dicts keep insertion order, so popitem() works last in, first out.
It raises KeyError. Check the dict first with if d: or while d:, or catch KeyError.
Get the first key with next(iter(d)) and pass it to pop(): d.pop(next(iter(d))). That removes the oldest pair.
No. Assigning to an existing key keeps its position. To move it to the end, pop it and assign it again.
Not since Python 3.7: it always removes the last inserted pair. In Python 3.6 and older the choice was arbitrary.

Next: dict.setdefault()

Return the value of a key, inserting a default first if the key is missing.

setdefault() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful