We are given a dictionary we need to remove the unwanted keys from the dictionary. For example, a = {'a': 1, 'b': 2, 'c': 3, 'd': 4} is a dictionary we need to remove the unwanted keys from the dictionary so that the output becomes {'a':1, 'c':3} .
Using del Statement
del statement is used to remove specific key-value pairs from a dictionary by specifying the key to delete. It modifies the dictionary in place and raises a KeyError if the key does not exist.
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
del a['b'] # Remove key 'b'
del data['d'] # Remove key 'd'
print(a)
Output
{'a': 1, 'c': 3}
Explanation:
- del statement removes the specified keys 'b' and 'd' from the dictionary data, eliminating their associated values.
- After the deletions, the dictionary is updated to only include the remaining key-value pairs, resulting in {'a': 1, 'c': 3}
Using Dictionary Comprehension
Dictionary comprehension allows filtering a dictionary by creating a new one with only the desired keys and values. This is done by iterating over the dictionary and including key-value pairs that meet the specified condition
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Set of keys to keep
b = {'a', 'c'}
# Dictionary comprehension to filter and retain only the keys present in 'b'
res = {key: a[key] for key in b}
print(res)
Output
{'c': 3, 'a': 1}
Explanation:
- Set b specifies the keys to keep, and the dictionary comprehension {key: a[key] for key in b} iterates through these keys extracting their corresponding values from the dictionary a.
- Resulting dictionary, res, includes only the key-value pairs for the keys 'a' and 'c', producing {'a': 1, 'c': 3}
Using pop()
pop() method removes a specific key from the dictionary and returns its value, modifying the dictionary in place. If the key doesn't exist a default value (like None) can be provided to avoid a KeyError.
a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
a.pop('b', None) # Remove 'b', ignore if not present
a.pop('d', None) # Remove 'd', ignore if not present
print(a)
Output
{'a': 1, 'c': 3}
Explanation:
- pop('b', None) and pop('d', None) statements remove the keys 'b' and 'd' from the dictionary a, along with their associated values, without raising an error if the keys are missing.
- After these operations, the updated dictionary contains only remaining key-value pairs, resulting in {'a': 1, 'c': 3}