Different ways of removing an item from Dictionary in Python




1. pop()

pop() method is used to remove an item from a dictionary.

mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11",
    "cost" : "$1000",
    "color" : "Black"
}
mydict.pop("color") # removes "color" : "Black" 
print(mydict)

Results

{'brand': 'iPhone', 'model': 'iPhone 11', 'cost': '$1000'}

2. del()

  • del() method is used to remove an item from a dictionary. This method raises an exception if the key is not present and you need to handle the exception while coding.
mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11",
    "cost" : "$1000",
    "color" : "Black" 
del mydict["color"] # removes "color" : "Black" 
print(mydict)

Results

{'brand': 'iPhone', 'model': 'iPhone 11', 'cost': '$1000'}
  • del keyword can also delete whole dictionary.
mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11",
    "cost" : "$1000",
    "color" : "Black" 
}
del mydict
print(mydict) # throws an error that 'mydict' is not defined
  • clear() is used to empty the dictionary items.
mydict = {
    "brand" :"iPhone",
    "model": "iPhone 11",
    "cost" : "$1000",
    "color" : "Black"
}
mydict.clear()
print(mydict) # prints {}