Python - Remove Dictionary Key Words
We are given a dictionary we need to remove the dictionary key words. For example we are given a dictionary d = {'a': 1, 'b': 2} we need to remove the dictionary key words so that the output becomes {'b': 2} . We can use method like del , pop and other methods to do it.
Using del
keyword
del keyword is used to remove a specific key-value pair from a dictionary by specifying the key. If the key exists, it will be deleted; otherwise, it raises a KeyError.
d = {'a': 1, 'b': 2}
# Remove the key-value pair where the key is 'a' from the dictionary
del d['a']
print(d)
Output
{'b': 2}
Explanation:
- Dictionary d is initialized with two key-value pairs: 'a': 1 and 'b': 2.
- del keyword is used to remove the key-value pair with key 'a', and the modified dictionary {'b': 2} is printed.
Using pop()
method
pop() method removes and returns the value associated with a specified key in a dictionary. If the key is not found, it raises a KeyError unless a default value is provided.
d = {'a': 1, 'b': 2}
# Remove the key-value pair where the key is 'a' and return its value
d.pop('a')
print(d)
Output
{'b': 2}
Explanation:
pop('a')
method removes key-value pair where the key is'a'
from the dictionaryd
and returns its value (1
in this case).- Modified dictionary
{'b': 2}
is then printed as it no longer contains key'a'
Using popitem()
popitem() method removes and returns the last key-value pair from a dictionary as a tuple. If the dictionary is empty, it raises a KeyError.
d = {'a': 1, 'b': 2}
# Removes the last key-value pair ('b': 2) from the dictionary
d.popitem()
print(d)
Output
{'a': 1}
Explanation:
- popitem() method removes and returns the last key-value pair ('b': 2) from the dictionary d.
- modified dictionary {'a': 1} is printed, which now only contains the key 'a'
Using Dictionary Comprehension
Dictionary comprehension allows you to create a new dictionary by applying an expression to each key-value pair of an existing dictionary.
d = {'a': 1, 'b': 2}
# Use dictionary comprehension to create a new dictionary excluding the key 'a'
d = {key: value for key, value in d.items() if key != 'a'}
print(d)
Output
{'b': 2}
Explanation:
- Dictionary comprehension iterates over the original dictionary d and creates a new dictionary, excluding the key 'a'.
- Modified dictionary, which now only contains the key 'b': 2, is printed.