You are currently viewing Remove Multiple keys from Python Dictionary

How to remove multiple keys from Python Dictionary? To remove multiple keys you have to create a list or set with the keys you want to delete from a dictionary and iterate it and use either the del keyword or the pop() function to delete each key from the list.

Advertisements

In this article, I will explain the del keyword, pop() function, dictionary comprehension, and for loop to remove the specified multiple keys from the dictionary with examples.

1. Quick Examples of Remove Multiple Keys from Dictionary

If you are in a hurry, below are some quick examples of how to remove multiple keys from the Dictionary.


# Quick examples of remove multiple keys from dictionary

# Example 1: Remove multiple keys using del keyword
keys_list = ['fee', 'discount', 'course']
for key in keys_list:
	del my_dict[key]

# Example 2:  Use pop() & list comprehension to
# remove multiple keys from dictionary
keys_list = ['fee', 'discount', 'course']
[my_dict.pop(key) for key in keys_list]

# Example 3: Remove multiple keys from dictionary 
my_dict = {key: my_dict[key] for key in my_dict if key not in keys_list}

# Example 4: Using items()along with list comprehension & dict()
# Remove multiple keys from dictionary
my_dict = dict([(key, val) for key, val in
		my_dict.items() if key not in keys_list])

# Example 5: Remove multiple keys using for loop
print("Before removing the key:\n", my_dict)
keys_list = ["course", "duration"]
for key in keys_list:
    del my_dict[key]

# Example 6:  Remove all keys using clear()
my_dict = {'course':'python','fee':4000,'duration':'60days'}
# empty the dictionary 
my_dict.clear()
print("Length", len(my_dict))

# Example 7: Remove all keys using del 
my_dict = {'course':'python','fee':4000,'duration':'60days'}

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key:value pair separated by commas. The dictionaries are indexed by keys.

Moreover, dictionaries are mutable data types, which means that you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value.

Let’s create a Python dictionary,


# Create dictionary
my_dict = {'course':'python','fee':4000,'duration':'60days','discount':1200}
print("Create dictionary:\n",my_dict)

Yields below output.

Remove multiple keys Python dictionary

3. Remove Multiple Keys from Dictionary

We can use a del keyword and for loop to remove the multiple keys from the dictionary in Python. First, we have to initialize the list of keys that we want to remove from the dictionary. Then using the del keyword we will remove the list of specified keys from the dictionary with the help of iterating. Here is an example. After removing the specified multiple key, I printed the remaining key-value pairs from the dictionary to the console.


# Create dictionary
my_dict = {'course':'python','fee':4000,'duration':'60days','discount':1200}

# Create removed keys list
keys_list = ['fee', 'discount', 'course']
print("Before removing the multiple keys: \n", my_dict)

# Remove multiple keys 
# Using del keyword and for loop
for key in keys_list:
	del my_dict[key]
print("After removing the multiple keys: \n", my_dict)

Yields below output. Note that removing a key actually removes the key and the value associated with it.

Remove multiple keys Python dictionary

4. Remove Multiple Keys from Dictionary using pop()

The Python dictionary pop() function is another method that can be used to remove the keys from the dictionary, this returns the value related to the removed key. If a key does not exist in the dictionary and the default value is specified, then returns the default value; else throws a KeyError.

Note that using the pop() function we can remove the single key at a time, but with the help of list comprehension you can delete multiple keys. Here, list comprehension iterates a list of specified multiple keys and removes them from the dictionary.

Let’s pop the specified key with help of list comprehension to remove list of multiple keys from the Python dictionary.


# Use pop() & list comprehension to
# remove multiple keys from dictionary
# Create removed keys list
keys_list = ['fee','discount','course']
[my_dict.pop(key) for key in keys_list]
print("After removing the multiple keys:\n", my_dict)

Yields the same output as above.

5. Remove Multiple keys using Dictionary Comprehension

Alternatively, we can use dictionary comprehension along with the if condition and not in operator we can remove specified multiple keys from the dictionary and return a new dictionary that contains the remaining key-value pairs of the dictionary.


# Remove multiple keys from dictionary 
my_dict = {key: my_dict[key] for key in my_dict if key not in keys_list}
print("After removing the multiple keys: \n", my_dict)

# Output:
# After removing the multiple keys: 
# {'duration': '60days'}

6. Remove Multiple keys from Dictionary using items() 

Using Python item() function along with dict() function and list comprehension we can also remove multiple keys from the dictionary. In this example, we create a new dictionary using dict() function instead of removal keys and using items() function we can extract key-value pairs and iterate them using list comprehension.


# Using items()along with list comprehension & dict()
# Remove multiple keys from dictionary
my_dict = dict([(key, val) for key, val in
		my_dict.items() if key not in keys_list])
print("After removing the multiple keys: \n", my_dict)

# Output:
# After removing the multiple keys:
# {'duration': '60days'}

7. Remove Multiple Keys using For Loop

We can also delete multiple keys by looping through the dictionary using for loop. It will iterate the list of specified multiple keys from the dictionary and then remove them using the del keyword.


# Remove multiple keys using for loop
print("Before removing the key:\n", my_dict)
keys_list = ["course", "duration"]
for key in keys_list:
    del my_dict[key]
print("After removing the keys:\n", my_dict)

# Output:
# Before removing the key:
#  {'course': 'python', 'fee': 4000, 'duration': '60days'}
# After removing the keys:
#  {'fee': 4000}

8. Remove All Keys using del

Using del keyword we can remove all key-value pairs from a dictionary.


# Remove all keys using del 
my_dict = {'course':'python','fee':4000,'duration':'60days'}

# empty the dictionary 
del my_dict

9. Delete all Keys from Dictionary using clear()

The Python dictionary clear() function is used to remove all key-value pairs from the dictionary. The clear() function doesn’t return any value.


# Remove all keys using clear()
my_dict = {'course':'python','fee':4000,'duration':'60days'}
# empty the dictionary 
my_dict.clear()
print("Length", len(my_dict))
print(my_dict)

# Output:
# Length 0
# {}

Frequently Asked Questions

How can I remove multiple keys from a Python dictionary?

You can use the pop() method to remove a specific key and its associated value from the dictionary. To remove multiple keys, you can use a loop or list comprehension along with the pop() method.

Can I remove multiple keys at once without using a loop?

You can remove multiple keys from a Python dictionary without using a loop by using the del statement along with unpacking.

What if I want to create a new dictionary without certain keys?

If you want to create a new dictionary without certain keys from an existing dictionary, you can use dictionary comprehension. For example, the dictionary comprehension iterates over the key-value pairs in the original my_dict, and it includes only those pairs where the key is not in the keys_to_remove list. The result is a new dictionary (new_dict) that does not contain the specified keys.

Can I remove keys in-place without creating a new dictionary?

You can remove keys in-place from a dictionary without creating a new dictionary. Two common methods to achieve this are using the del statement and the dict.pop() method.

Is there a way to remove keys while iterating over the dictionary?

It’s generally not recommended to modify a dictionary while iterating over it. To achieve this, you can create a list of keys to remove during the iteration and then remove them outside the loop.

What happens if I try to remove a key that doesn’t exist in the dictionary?

If you use the pop() method and specify a key that doesn’t exist, it will raise a KeyError. To avoid this, you can provide a default value as the second argument to pop() or use the get() method.

Conclusion

In this article, I have explained the Python del keyword, pop() function, dict comprehension, and for loop to remove the specified multiple keys from Python dictionary with examples.

Happy learning !!

Related Articles

References