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'