Open In App

Python – Remove Multiple Keys from Dictionary

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and our task is to remove multiple keys from the dictionary. For example, consider a dictionary d = {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4} where we want to remove the keys ‘b’ and ‘d’, then the output will be {‘a’: 1, ‘c’: 3}. Let’s explore different methods to remove multiple keys from a dictionary efficiently.

Dictionary Comprehension

Using dictionary comprehension is one of the most efficient ways to remove multiple keys. It creates a new dictionary excluding the specified keys.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Keys to remove
key_rmv = {'b', 'd'}

# Remove keys using dictionary comprehension
d = {k: v for k, v in d.items() if k not in key_rmv}

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • dictionary comprehension iterates through the dictionary using .items() and includes only the keys not present in key_rmv.
  • This method is efficient as it avoids modifying the dictionary directly and works well for larger dictionaries.

Let’s explore some more methods and see how we can remove multiple keys from dictionary.

Using dict.pop()

We can use the pop() method to remove keys from the dictionary one by one in a loop.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Keys to remove
key_rmv = ['b', 'd']

# Remove keys using pop in a loop
for key in key_rmv:
    d.pop(key, None)  # Use None to avoid KeyError

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • pop() method removes the specified key from the dictionary.
  • Using None as the second argument ensures no error is raised if a key is not present.

Using del()

del() keyword can also be used to delete keys from the dictionary in a loop.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Keys to remove
key_rmv = ['b', 'd']

# Remove keys using del in a loop
for key in key_rmv:
    if key in d:  # Check if the key exists
        del d[key]

print(d)

Output
{'a': 1, 'c': 3}

Explanation:

  • del() keyword directly deletes the key-value pair from the dictionary.
  • A conditional check ensures the key exists before deletion to avoid errors..

Using filter() with Lambda Function

filter() function combined with a lambda function can create a new dictionary excluding the specified keys.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Keys to remove
key_rmv = {'b', 'd'}

# Remove keys using filter
d = dict(filter(lambda item: item[0] not in key_rmv, d.items()))

print(d)

Output
{'a': 1, 'c': 3}

Explanation: filter() function applies a condition to each key-value pair and the condition checks if the key is not in key_rmv.



Next Article

Similar Reads