Skip to content
Home » Dictionary Methods – pop and popitem

Dictionary Methods – pop and popitem

Spread the love

Today we’ll start discussing the most important dictionary methods.

Here’s the video version of the article:

The pop Method

The first method we’re going to talk about is pop.

Just like with lists, we can use the pop(key) method. It returns the value corresponding to the key and removes the pair:

>>> positions = {"Lucy" : 5, "Michelle" : 2, "Alice" : 1, "Samantha" : 3, "Clara" : 4}
>>> alice_position = positions.pop("Alice")
>>> alice_position
1

>>> positions
{'Lucy': 5, 'Michelle': 2, 'Samantha': 3, 'Clara': 4}

The popitem Method

The popitem method returns (and removes from the dictionary) an arbitrary key-value pair as a tuple:

>>> cars = {"Mike" : "Porsche", "Amanda" : "Buick", "Sarah" : "Mazda", "Ron" : "Renault", "William" : "Lamborghini"}
>>> (owner, car) = cars.popitem()
>>> (owner, car)
('William', 'Lamborghini')

Each time we use popitem, the dictionary shrinks.

>>> cars.popitem()
('Ron', 'Renault')

>>> cars.popitem()
('Sarah', 'Mazda')

>>> cars.popitem()
('Amanda', 'Buick')

>>> cars.popitem()
('Mike', 'Porsche')

If the dictionary is empty, trying to use popitem results in an error:

>>> cars
{}

>>> cars.popitem()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply