Python Tutorial

Deleting Elements from Python Dictionary

How to Delete Elements from a Dictionary in Python?

To remove elements from a Python dictionary, use one of the following methods:

Using del() method

The del keyword removes the item with a particular key name.

Example:

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

del thisdict["model"]

print(thisdict)

Output:

{'brand': 'Ford', 'year': 1964}

Using pop() method

The item with the supplied key name is removed using the pop() method.

Example: 

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

thisdict.pop("model")

print(thisdict)

Output:

{'brand': 'Ford', 'year': 1964}

Using popitem() method

The popitem() method removes the last inserted item (a random item is deleted in versions prior to 3.7).

Example:

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

thisdict.popitem()

print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang'}

Using clear() method

The clear() method empties the dictionary.

Example:

 

thisdict = {

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

thisdict.clear()

print(thisdict)

 

Output:

{}
Did you find this article helpful?