How to Remove an Element From Dictionary in Python

Here are the ways to remove an element from a dictionary in Python:

  1. Using the “del” statement
  2. Using the “dict.pop()” method
  3. Using the “popitem()” method
  4. Using the “clear()” method

Method 1: Using the “del” statement

To remove an element from a dictionary using the del statement, “specify the key of the element you want to remove after the del keyword”. The element with the specified key will be removed from the dictionary. If the key is not found in the dictionary, a KeyError will be raised.

Example

main_dict = {'A': 1, 'B': 2, 'C': 3}

# Remove the element with the key 'B'
del main_dict['B']

print(main_dict)

Output

{'A': 1, 'C': 3}

Method 2: Using the “dict.pop()” method

The “dict.pop()” method allows you to remove an element with a specified key and return its value. You must pass the key of the element you want to remove as an argument to the pop() method.

If the key is not found in the dictionary, a KeyError will be raised. However, you can also provide a default value as a second argument to the pop() method, which will be returned instead of raising a KeyError when the key is not found in the dictionary.

Example

main_dict = {'A': 1, 'B': 2, 'C': 3}

# Remove the element with the key 'B'
main_dict.pop('B')

print(main_dict)

Output

{'A': 1, 'C': 3}

The “dict.pop()” method removes the element with the specified key and returns its value. If the key is not found, a KeyError will be raised.

main_dict = {'A': 1, 'B': 2, 'C': 3}

# Remove the element with the key 'B'
main_dict.pop('D')

print(main_dict)

Output

KeyError: 'D'

Method 3: Using the popitem() method

The popitem() method “removes an element from the dictionary and returns its key and value as a tuple, (key, value).”

Example

cars = {"Volksvagen": "Audi", "Tata Motors": "Jaguar"}

cars.popitem()
print(cars)

Output

{'Volksvagen': 'Audi'}

Method 4: Using the clear() method

The clear() method removes all elements from a dictionary, making it empty.

Example

cars = {"Volksvagen": "Audi", "Tata Motors": "Jaguar"}

cars.clear()
print(cars)

Output

{}

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.