3.8.2. Adding and removing entries#

Accessing a dictionary using a key that is not part of the dictionary results in a key error:

dict_of_integers = {1: 11, 2: 22, 5: 55}
dict_of_integers[3]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 dict_of_integers[3]

KeyError: 3

However, assigning a value to a key that does not exist creates this key. This is in fact how we add entries to a dictionary:

dict_of_integers[3] = 33

dict_of_integers
{1: 11, 2: 22, 5: 55, 3: 33}

To remove an entry from a dictionary, we use the pop method, which behaves as the list’s pop method. It returns the value being deleted, and removes this entry from the dictionary.

print(dict_of_integers.pop(1))  # Remove the element with key 1
print(dict_of_integers)
11
{2: 22, 5: 55, 3: 33}