Deleting dictionary entries
Deleting dictionary keys
Earlier we saw that we could use list’s .pop()
method to remove an element from a list, removing either the last element in the list (the default, when no argument is supplied), or at a specific index (if we supply an argument).
Dictionaries are mutable, and thus, like lists, they can be changed. Dictionaries also support .pop()
but it works a little differently than it does with lists. The .pop()
method for dictionaries requires a valid key as an argument. This is because dictionaries don’t have the same sense of linear order as a list—everything is based on keys.
So this works:
>>> d = {'foo': 'bar'}
>>> d.pop('foo')
'bar'
but this does not:
>>> d = {'foo': 'bar'}
>>> d.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop expected at least 1 argument, got 0
Python also provides the keyword del
which can be used to remove a key from a dictionary.
>>> pets = {'fluffy': 'gerbil', 'george': 'turtle',
... 'oswald': 'goldfish', 'wyatt': 'ferret'}
>>> del pets['oswald'] # RIP oswald :(
>>> pets
{'fluffy': 'gerbil', 'george': 'turtle', 'wyatt': 'ferret'}
But be careful! If you do not specify a key, the entire dictionary will be deleted!
>>> pets = {'fluffy': 'gerbil', 'george' : 'turtle',
... 'oswald': 'goldfish', 'wyatt': 'ferret'}
>>> del pets # oops!
>>> pets
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pets' is not defined
Notice also that .pop()
with a key supplied will return the value associated with that key and then remove the key/value pair. del
will simply delete the entry.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.