- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the best way to remove an item from a Python dictionary?
You can use the del function to delete a specific key or loop through all keys and delete them. For example,
my_dict = {'name': 'foo', 'age': 28} keys = list(my_dict.keys()) for key in keys: del my_dict[key] print(my_dict)
This will give the output:
{}
You can also use the pop function to delete a specific key or loop through all keys and delete them. For example,
my_dict = {'name': 'foo', 'age': 28} keys = list(my_dict.keys())
for key in keys:
my_dict.pop(key) print(my_dict)
This will give the output:
{}
Advertisements