Remove Dictionary Elements in Python

Remove Dictionary Elements in Python

Hello Techies,

In this tutorial, we will learn about How to Remove Dictionary elements in Python with the help of examples.

In my previous blog, I covered How to remove element from list in Python topic.

Let’s check different ways to remove a key from the dictionary one by one.

Ways to Remove Dictionary Elements in Python

The dictionary stores the data in the key: value pairs. A dictionary is a collection that is ordered, changeable, and does not allow duplicates.

We can use a del keyboard, pop() method, and clear() method to remove dictionary elements in Python. Let’s understand each of them one by one with the help of an example.

del keyword to remove Dictionary elements in Python

del keywords can be used to delete a specific key from a dictionary or you can delete an entire dictionary. One drawback that can be considered for its use is that if the key is not found, it raises an exception. Check the examples below

The syntax of a del keyword is:

del dict[key]
# or
del dict_name

Parameters used in del keyword

  • You can pass the key if you want to remove the specific key.
  • If you want to remove the dictionary completely, pass the name of the dictionary followed by the del keyword.

Example 1: Delete key from dictionary Python

# Program Remove Dictionary elements in Python using del keyword

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before delete:', data)

# Deleting dictionary key
del data["A"]
print('data dictionary after delete:', data)

Output:

data dictionary before delete: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
data dictionary after delete: {'B': 2, 'C': 3, 'D': 4}

Example 2: Delete complete dictionary in Python

# Program Remove Dictionary elements in Python using del keyword

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before delete:', data)

# Deleting dict key
del data
print('data dictionary after delete:', data)

Output:

data dictionary before delete: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Traceback (most recent call last):
  File "C:\Users\Pranali\Desktop\test\test1.py", line 9, in <module>
    print('data dictionary after delete:', data)
NameError: name 'data' is not defined

The dictionary has been completely deleted here, so in the above output you will get an error saying ‘no data defined’.


pop()

The pop() method is used to delete specific keys from the dictionary.

The syntax of the pop() method is:

dictionary.pop(key[, default])
Parameters used in pop() method

The pop() method takes two parameters:

  • key: Required. The name of the key you want to remove.
  • default: Optional. The value to get if the specified key does not exist.
pop() method returns:
  • If the key is found. The elements removed from the dictionary
  • If the key is not found. The value specified as the second argument (default)
  • If the key is not found and the default argument is not specified – a KeyError exception will be raised.

Example 1: Remove Dictionary elements in Python using pop() method

# Program Remove Dictionary elements in Python using pop() method

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before pop:', data)

# Deleting dict key
data.pop('D')
print('data dictionary after pop:', data)

Output:

data dictionary before pop: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
data dictionary after pop: {'A': 1, 'B': 2, 'C': 3}

Example 2: Remove Dictionary elements in Python using pop() method for the non-existing key, provided a default value.

# Program Remove Dictionary elements in Python
# using a pop() method using the non-existing key.
# provided a default value.

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before pop:', data)

# Deleting dict key
data.pop('F', None)
print('data dictionary after pop:', data)

Output:

data dictionary before pop: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
data dictionary after pop: {'A': 1, 'B': 2, 'C': 3, 'D': 4}

Example 3: Remove Dictionary elements in Python using pop() method for the non-existing key

# Program Remove Dictionary elements in Python 
# using a pop() method using the non-existing key.

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before pop:', data)

# Deleting dict key
data.pop('F')
print('data dictionary after pop:', data)

Output:

data dictionary before pop: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Traceback (most recent call last):
  File "C:\Users\Pranali\Desktop\test\test1.py", line 9, in <module>
    data.pop('F')
KeyError: 'F'

clear()

The clear() method used to remove all elements from the dictionary.

The syntax of the clear() method is:

dict.clear()

The clear method takes no parameters.

Example: How do you clear a dictionary in python?

# Program Remove Dictionary elements in Python
# using clear() method

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before clear:', data)

# Deleting dict key
data.clear()
print('data dictionary after clear:', data)

Output:

data dictionary before clear: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
data dictionary after clear: {}

popitem()

The Python popitem() method used to remove the last element (key, value) inserted into the dictionary.

The popitem() method removes the dictionary (key, value) pair in the Last in, First Out (LIFO) order.

The syntax of the popitem() method is:

dict.popitem()

popitem() does not take any parameters.

Example:

# Program Remove Dictionary elements in Python
# using popitem() method

# Creating dictionary
data = {"A": 1, "B": 2, "C": 3, "D": 4}
print('data dictionary before clear:', data)

# Deleting dict key
data.popitem()
print('data dictionary after clear:', data)

Output:

data dictionary before clear: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
data dictionary after clear: {'A': 1, 'B': 2, 'C': 3}

Remove multiple keys from dictionary Python

Method 1:

# Creating dictionary
data = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

# Creating remove keys list
rem_list = ['A', 'C', 'D']

print('Original dictionary:', data)

# using list comprehension to remove multiple keys from dictionary.
result = dict([(key, val) for key, val in
           data.items() if key not in rem_list])
print('Dictionary after removal keys:', result)

Output:

Original dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Dictionary after removal keys: {'B': 2}

Method 2:

# Creating dictionary
data = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

# Creating remove keys list
rem_list = ['A', 'C', 'D']

print('Original dictionary:', data)

# using Using pop() + list comprehension
# to remove multiple keys from the dictionary.

[data.pop(key) for key in rem_list]
print('Dictionary after removal keys:', data)

Output:

Original dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Dictionary after removal keys: {'B': 2}

Python delete dictionary key while iterating

Method 1:

# Creating dictionary
data = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
print('Original dictionary:', data)

to_del = [key for key in data if key in('A', 'C', 'D')]

# Delete keys
for key in to_del:
    del data[key]
print('Modified dictionary:', data)

Output:

Original dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Modified dictionary: {'B': 2}

Method 2:

# Creating dictionary
data = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
print('Original dictionary:', data)

# Iterating through the list of keys
for key in list(data):
    if key == 'B':
        del data[key]

print('Modified dictionary:', data)

Output:

Original dictionary: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Modified dictionary: {'A': 1, 'C': 3, 'D': 4}

Conclusion

In this tutorial, you learned about Remove Dictionary elements in Python, We have covered the following points:

  • Python del keyword
  • Python pop() method
  • Python clear() method
  • Python popitem() method
  • Remove multiple keys from dictionary Python
  • Python delete dictionary key while iterating

Leave a Comment