Remove a key from a Python dictionary
This post will discuss how to remove a key from a dictionary in Python.
1. Using d.pop() function
The standard Pythonic solution to remove a key from the dictionary is using the pop() function.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} key = 'B' d.pop(key) print(d) # {'A': 1, 'C': 3} |
If the key is not found in the dictionary, a KeyError is raised. To avoid it, use the two-argument form of pop(key[, default]), which returns the additional default parameter when the key does not exist.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} key = 'D' d.pop(key, None) print(d) # {'A': 1, 'B': 2, 'C': 3} |
If you need to remove multiple keys from a dictionary, you can use a list comprehension instead:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} keys = ['B', 'C'] [d.pop(x, None) for x in keys] print(d) # {'A': 1} |
2. Using del statement
Alternatively, you can use the del d[k] syntax to remove a key k from the dictionary d.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} key = 'B' del d[key] print(d) # {'A': 1, 'C': 3} |
This raises a KeyError if the key is not in the dictionary. To avoid the exception, use del d[key] with try/except block, as shown below. However, this just adds more complexity to the code. Therefore, the two-arg pop() is recommended over del.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} key = 'D' try: del d[key] except KeyError: pass print(d) # {'A': 1, 'B': 2, 'C': 3} |
That’s all about removing a key from a Python dictionary.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)