Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.popitem() method

Reference for Python dict.popitem(): remove and return the last inserted key-value pair, LIFO order, the KeyError on empty dicts and a draining loop.

The popitem() method removes one key-value pair from a dictionary and returns it as a tuple (key, value). Pairs come out in LIFO order: the most recently inserted pair is removed first. Since Python 3.7 dictionaries remember insertion order, so this behavior is guaranteed.

Because it takes no key, popitem() is handy for draining a dictionary, for treating one as a stack of pairs, or for taking "any" item when you do not care which. Calling it on an empty dictionary raises KeyError.

Python
stock = {"apple": 3, "pear": 5}
stock.popitem()   # ('pear', 5)

Try it

Python Removing the newest pair

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 Draining a dictionary

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.popitem()
Name Description
(none) The method takes no arguments.

Return value: a (key, value) tuple for the removed pair.

Raises: KeyError if the dictionary is empty.

Usage notes

  • It mutates the dictionary. The pair is removed in place; the return value is the only record of it.
  • LIFO order is guaranteed from Python 3.7. Older versions removed an arbitrary pair, so very old code may not assume an order.
  • Updating an existing key does not move it. d["a"] = 9 keeps "a" at its original position, so it is not necessarily the next one popped. Delete and re-insert a key if you want it to become the newest.
  • Empty dictionaries raise KeyError. Test with while d: or catch the error. The message is 'popitem(): dictionary is empty'.
  • Need the oldest pair instead? Use next(iter(d.items())) to look at it and d.pop(key) to remove it, or an OrderedDict and its popitem(last=False).
  • To remove a specific key, use dict.pop() or del d[key].