Summary: You can use one of these methods to delete multiple keys from a dictionary Python –
(1) Iterate across the list of keys to be deleted and use the syntax del dict[‘key’]
(2) Iterate across the list of keys to be deleted and call the dictionary.pop(key)
method.
(3) Eliminate unrequired keys and reconstruct the original dictionary using a dictionary comprehension.
(4) Use map and pop methods.
Problem Formulation
Consider that you have a Python dictionary that has certain key-value pairs. How will you remove multiple keys from the given dictionary?
Removing multiple keys from a Python dictionary leads to the deletion of all the specified key-value pairs with respect to the specified keys leaving the dictionary with only those key-value pairs that have not been removed. Let us visualize the given problem with the help of an example.
Example:
Given: my_dictionary = {‘key_1’: ‘value_1’, ‘key_2’: ‘value_2’, ‘key_3’: ‘value_3’, ‘key_4’: ‘value_4’, ‘key_5’: ‘value_5’} Challenge: Remove the keys: ‘key_1’ and ‘key_3’ Expected Output: {‘key_2’: ‘value_2’, ‘key_4’: ‘value_4’, ‘key_5’: ‘value_5’} |
Related Read: Delete an Element in a Dictionary | Python
Without further ado, let’s dive into the solutions to the programming challenge.
⦿ Method 1: Using a ‘For Loop’ and the ‘del’ Keyword
The del keyword along, with the specified key, allows us to remove elements from a dictionary.
Approach: Store the keys to be removed in a list and then use a ‘for loop’ to iterate across all the elements of this. Now access the elements within the given dictionary using each key and delete them using the “del” keyword using the syntax: del dictinary[key]
Code:
my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } remove_keys = ['key_1', 'key_3'] for key in remove_keys: del my_dictionary[key] print(my_dictionary)
Output:
{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}
⦿ Method 2: Using a ‘For Loop’ and the ‘pop’ Keyword
Approach: Store the keys to be removed within a list. Then, use a for loop across the list of keys, and at each iteration, call the dictionary.pop(key)
method to remove a specific key from the given dictionary.
Code:
my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } remove_keys = ['key_1', 'key_3'] for key in remove_keys: my_dictionary.pop(key) print(my_dictionary)
Output:
{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}
One-Liner: There’s a more concise way of formulating the above solution in a single line of code. Here’s how to do it:
# Given Data my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } # One-Liner [my_dictionary.pop(key) for key in ['key_1', 'key_3']];print(my_dictionary)
⦿ Method 3: One-Line Solution Using Dictionary Comprehension
Approach: Iterate across all the keys in the dictionary except the ones that you want to delete using a dictionary comprehension and then store only the required key-values in the dictionary. Therefore, this technique automatically eliminates the key-value pairs to be removed from the dictionary.
Code:
my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } # One-liner my_dictionary = {i: my_dictionary[i] for i in my_dictionary if i not in ['key_1', 'key_3']} # Display result print(my_dictionary)
Output:
{'key_2': 'value_2', 'key_4': 'value_4', 'key_5': 'value_5'}
Explanation: Let’s dissect the one-liner to understand how it works. The expression stores the key-value pairs in the dictionary that you do not want to delete. To eliminate the specified keys we have the context variable “i” that denotes each key that has to be eliminated. The for loop allows you to only consider the required keys with the help of the conditional if statement which helps you to ignore the specified keys. Thus, you can think of this as an eliminate and conquer technique!
An alternate formulation that uses a similar logic is as follows:
my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } my_dictionary= dict([(key, val) for key, val in my_dictionary.items() if key not in ['key_1', 'key_3']]) print(my_dictionary)
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
⦿ Method 4: Using pop and map
This might not be the most Pythonic solution. Nevertheless, it solves the purpose and yields us the output that we desire.
Approach: The idea is to store the keys to be eliminated in a list and then use the map() method. Pass the dictionary.pop()
method as the first argument to the map method while the second argument should be an iterable and in this case the second argument/iterable is the list containing the keys to be removed.
Code:
my_dictionary = { 'key_1': 'value_1', 'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4', 'key_5': 'value_5' } remove_keys = ['key_1', 'key_3'] list(map(my_dictionary.pop, remove_keys)) print(my_dictionary)
TIDBIT: The map()
function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.
Read more about map method here: Python map() — Finally Mastering the Python Map Function [+Video]
Conclusions
We have successfully conquered the given programming challenge and solved it using as many as four different ways. I hope this tutorial helped you. Please subscribe and stay tuned to unearth new concepts every day.
Happy coding! 🙂
Finxter Computer Science Academy
- One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
- So, do you want to master the art of web scraping using Python’s BeautifulSoup?
- If the answer is yes – this course will take you from beginner to expert in Web Scraping.