#11
Inspired Python
>>> d = {"favorite_food": "Pizza", "favorite_drink": "Coffee"}
>>> d.pop("favorite_food")
'Pizza'
# Missing elements raise KeyError, like you would expect.
>>> d.pop("favorite_music")
KeyError: 'favorite_music'
# ... but like the get() method you can specify a default.
>>> d.pop("favorite_language", "Python")
'Python'
>>> d['favorite_city'] = "London"
>>> d.popitem()
('favorite_city', 'London')

Python Dictionary Tricks: Popping items


You can use the pop(key) method to remove (and return) the value of an item in a dictionary. It is very useful if you want to destructively retrieve an item from a dictionary and remove it at the same time. You can also use popitem() to return a (key, value) tuple of the last inserted entry in the dictionary.

Be Inspired Get Python tips sent to your inbox

We'll tell you about the latest courses and articles.

Absolutely no spam. We promise!