![]() |
VOOZH | about |
We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove the items with value "10" then the output will be {"b": 20, "d": 30}
Dictionary comprehension is an efficient way to filter out key-value pairs by value. It creates a new dictionary containing only the items we want to keep.
{'a': 1, 'c': 3}
Explanation: We iterate over all key-value pairs using d.items() and the condition v != 2 ensures that only items with values not equal to 2 are included in the new dictionary, then the original dictionary is updated with the filtered result.
Let's explore some more methods and see how we can remove item from dictionary by value.
This method involves finding the key associated with the value and then using the del() keyword to remove the key-value pair.
{'a': 1, 'c': 3}
Explanation:
This approach involves iterating through the dictionary to find the key with the specified value using for loop and then using pop() to remove it.
{'a': 1, 'c': 3}
Explanation:
The filter() function can also be used to create a filtered version of the dictionary by excluding items with the specified value.
{'a': 1, 'c': 3}
Explanation: