How to Delete an Item from a Dictionary in Python

Created
Modified

Using del Statement

The easiest way to delete an item from a dictionary in Python:

#!/usr/bin/python3

m = {"a":1, "b":2}

# remove a
if 'a' in m:
  del m['a']
print(m)
{'b': 2}

Using pop Method

If key is in the dictionary, remove it and return its value, else return default. For example,

#!/usr/bin/python3

m = {"a":1, "b":2}

# remove a
if 'a' in m:
  # dict.pop(key[, default])
  m.pop('a')
print(m)
{'b': 2}

And both of them will raise a KeyError if the key you're providing to them is not present in the dictionary.

Python Errors

Raise a KeyError:

del m['c']
  del m['c']
KeyError: 'c'

Related Tags