In this article we will discuss diiferent ways to delete a key from dictionary in python.

Suppose we have a dictionary of string and int i.e.

# Dictionary of strings and int
wordFreqDic = {
    "Hello": 56,
    "at" : 23 ,
    "test" : 43,
    "this" : 43
    }

Now we want to remove an item from dictionary whose key is “at”. Let’s see how to do that,

Remove a key from dictionary using del

del d[key]

del statement removes the given item from the dictionary. If given key is not present in dictionary then it will throw KeyError.

Let’s use it to remove the key from above mentioned dictionary,

''' 
Deleting an entry from dictionary using del 
'''
# If key exist in dictionary then delete it using del.
if "at" in wordFreqDic:
    del wordFreqDic["at"]
    
print("Updated Dictionary :" , wordFreqDic)      

Output:
Updated Dictionary : {'Hello': 56, 'test': 43, 'this': 43}

It’s necessary to check if key is present in dictionary before deletion otherwise del with throw keyError.

Deleting key from dictionary using del and try/except

If we don’t want of add if check before calling del, we can use try/except too. Let’s try to delete a key that does not exist in dictionary and catch the error too i.e.

''' 
Deleting an entry from dictionary using del and try/except  
'''
# If key is not present in dictionary, then del can throw KeyError
try:
    del wordFreqDic["testing"]
except KeyError:
    print("Key 'testing' not found")

Output:
Key 'testing' not found

Remove a key from dictionary using dict.pop()

dict.pop(key[, default])

  • If key exists in dictionary then dict.pop() removes the element with given key from dictionary and return its value.
  • If given key doesn’t exist in dictionary then it returns the given Default value.
  • If given key doesn’t exist in dictionary and No Default value is passed to pop() then it will throw KeyError

Let’s delete an element from dict using pop()

''' 
Deleting an entry from dictionary using pop() 
'''    

# As 'this' key is present in dict, so pop() will delete its entry and return its value    
result = wordFreqDic.pop("this", None)    

print("Deleted item's value = ", result)
print("Updated Dictionary :" , wordFreqDic)   

Output:
Deleted item's value =  43
Updated Dictionary : {'Hello': 56, 'test': 43}

Let’s delete an element that is not present in dictionary using pop()
# Trying to delete an element from dict, which is not present.
# It will return given default value i.e. None     
result = wordFreqDic.pop("testing", None)    

print("Deleted item's value = ", result)
print("Updated Dictionary :" , wordFreqDic)

Output:
Deleted item's value = None
Updated Dictionary : {'Hello': 56, 'test': 43}

It will return given default value i.e. None

Default value in pop() is neccesary, because if given key is not present in dictionary and no default value is given in pop() then it will throw keyError.

Deleting key from dictionary using pop() and try/except

Let’s delete an element that is not present in dictionary using pop() and without passing default value argument in pop() i.e.

# Trying to delete an element from dict, which is not present.
# Also, if we don't pass any default value then it will throw KeyError.     

try:
    wordFreqDic.pop("testing")    
except KeyError:
    print("Key not found")    

Output:
key not found

Complete Series of Python Dictionary tutorials,

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

def main():
    
    # Dictionary of strings and int
    wordFreqDic = {
        "Hello": 56,
        "at" : 23 ,
        "test" : 43,
        "this" : 43
        }
    
    print("Original Dictionary :" , wordFreqDic)   
    
    
    ''' 
    Deleting an entry from dictionary using del 
    '''
    # If key exist in dictionary then delete it using del.
    if "at" in wordFreqDic:
        del wordFreqDic["at"]
        
    print("Updated Dictionary :" , wordFreqDic)      
    
    
    ''' 
    Deleting an entry from dictionary using del and try/except  
    '''
    # If key is not present in dictionary, then del can throw KeyError
    try:
        del wordFreqDic["testing"]
    except KeyError:
        print("Key 'testing' not found")
        
    
    ''' 
    Deleting an entry from dictionary using pop() 
    '''    
    
    # As 'this' key is present in dict, so pop() will delete its entry and return its value    
    result = wordFreqDic.pop("this", None)    
    
    print("Deleted item's value = ", result)
    print("Updated Dictionary :" , wordFreqDic)   
        
    
    # Trying to delete an element from dict, which is not present.
    # It will return given default value i.e. None     
    result = wordFreqDic.pop("testing", None)    
    
    print("Deleted item's value = ", result)
    print("Updated Dictionary :" , wordFreqDic)   
    
    
    # Trying to delete an element from dict, which is not present.
    # Also, if we don't pass any default value then it will throw KeyError.     
    
    try:
        wordFreqDic.pop("testing")    
    except KeyError:
        print("Key not found")    
    
            
    
    
if __name__ == '__main__':
    main()

Output:
Original Dictionary : {'this': 43, 'at': 23, 'Hello': 56, 'test': 43}
Updated Dictionary : {'this': 43, 'Hello': 56, 'test': 43}
Key 'testing' not found
Deleted item's value =  43
Updated Dictionary : {'Hello': 56, 'test': 43}
Deleted item's value =  None
Updated Dictionary : {'Hello': 56, 'test': 43}
Key not found