How to Remove a Key from a Dictionary in Python
Table of Contents
Dictionaries in Python are extremely useful because they allow you to store data in key-value pairs.
After you create your dictionary, you can add elements by providing a key and a value.
However, you can also remove elements from a dictionary by providing a key.
In this post, we'll learn how to remove elements from a dictionary by key in Python.
How to remove an element by key
To start, let's look at initializing an example dictionary:
PYTHONplaces = {
"Paris": "France",
"London": "England",
"New York": "USA",
"Tokyo": "Japan"
}
print(places)
BASH{'Paris': 'France', 'London': 'England', 'New York': 'USA', 'Tokyo': 'Japan'}
In this example, the key is the city name and the value is the country name.
Let's say you wanted to remove Paris
from the dictionary.
Since that is already the key, you can use it with the del
keyword.
PYTHONplaces = {
"Paris": "France",
"London": "England",
"New York": "USA",
"Tokyo": "Japan"
}
del places["Paris"]
print(places)
BASH{'London': 'England', 'New York': 'USA', 'Tokyo': 'Japan'}
Keep in mind that when you use the del
keyword, it will mutate the dictionary for all references.
This is fine because this is usually what you want to happen.
Conclusion
In this post, we learned how to remove elements from a dictionary by key in Python.
Simply use the del
keyword to remove an element from a dictionary by passing in the key that you want removed.
Thanks for reading and happy coding!
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js