Delete (Remove) an item from a dictionary in Python - How to use pop, del, clear

To delete an item from a dictionary, you can use pop(), del(), clear() methods.

pop()

d = {'A': 2, 'B': 5, 'C': 13}

p = d.pop('B')

print(d)  # {'A': 2, 'C': 13}
print(p)  # 5

The pop() deletes the pair by the key and returns its value. You can't remove the key that the dictionary doesn't have. If you pop the nonexistent key, Python raises the KeyError exception.

d = {'A': 2, 'B': 5, 'C': 13}

d.pop('D')

# KeyError: 'D'

del()

d = {'A': 2, 'B': 5, 'C': 13}

del d['C']

print(d)  # {'A': 2, 'B': 5}

The del() is a Python built-in function that deletes an element by a key. It raises the exception if the key doesn't exist.

d = {'A': 2, 'B': 5, 'C': 13}

del d['D']

# KeyError: 'D'

clear()

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
d.clear()

print(d)  # {}

The clear() removes all items from a dictionary. The id of the dictionary doesn't change after clearing.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

print(id(d))  # 4408171776

d.clear()

print(id(d))  # 4408171776

Python Dictionary

Python Tutorial