Remove Key from List of Dictionaries in Python (Example)
In this tutorial, you’ll learn how to remove a key from a list of dictionaries in Python. Removing a key from dictionaries within a list can be useful when you want to selectively eliminate a specific key-value pair. We’ll explore different examples to demonstrate this process.
The table of contents is structured as follows:
Let’s dive into it!
Initializing a Sample List of Dictionaries
Firstly, let’s initialize a sample list of dictionaries that we’ll be working with throughout the tutorial:
# Initializing a sample list of dictionaries my_list = [ {'name': 'John', 'age': 25, 'city': 'New York'}, {'name': 'Emily', 'age': 30, 'city': 'London'}, {'name': 'Michael', 'age': 40, 'city': 'Paris'} ]
This creates a list, my_list
, which contains dictionaries representing individuals with their respective attributes.
Example: Removing a Key from All Dictionaries
To remove a key from all dictionaries in the list, we’ll iterate over each dictionary and use the del keyword to delete the specific key. Here’s an example:
# Remove the 'age' key from all dictionaries key_to_remove = 'age' for dictionary in my_list: del dictionary[key_to_remove] </strong> print(my_list) #[ {'name': 'John', 'city': 'New York'}, # {'name': 'Emily', 'city': 'London'}, # {'name': 'Michael', 'city': 'Paris'}]
In this example, we specify the key we want to remove using the variable key_to_remove
. We then iterate over each dictionary in the list using a for loop.
Inside the loop, we use the del
keyword followed by the dictionary name and key_to_remove
to delete the key-value pair from each dictionary. As you can see, the age
key has been removed from all dictionaries within the list.
Video, Further Resources & Summary
In this tutorial, we explored an example of how to remove a key from a list of dictionaries in Python. By using the del keyword and iterating over each dictionary, we can selectively eliminate specific keys from all dictionaries within the list.
Do you need more explanations on looping through a list of integers in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
The YouTube video will be added soon.
For more Python programming tutorials and examples, you can check out the following resources on Statistics Globe:
- Iterate Over Nested Dictionary with List in Python (Example)
- How to Use Lists in Python (13 Examples)
- Convert Dictionary to List in Python (3 Examples)
- Are Dictionaries Faster than Lists in Python?
- Convert Dictionary Keys to List & Vice Versa in Python (Examples)
Now you have the knowledge and techniques to remove a key from a list of dictionaries in Python. Happy coding!
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter