How To Remove A Dictionary From A List In Python

In this tutorial, we will learn how to remove a dictionary from a list in Python. This can be useful when you have a list containing dictionaries, and you want to remove a specific dictionary based on a certain condition or value.

Step 1: Create a List of Dictionaries

First, let’s create a list of dictionaries. We will create a list called my_list containing four dictionaries with keys id and name.

Step 2: Use a List Comprehension to Remove the Dictionary from the List

We will use a list comprehension to create a new list after removing a dictionary with a specific id. In this example, we will remove the dictionary with id = 3.

Now, my_list should be:

Alternative: Using a Regular for Loop

Another way to remove a dictionary from a list is to use a regular for loop with the .remove() method. We first find the dictionary we want to remove, then remove it.

This will result in the same list as in the previous step, with the dictionary with id = 3 removed.

Full Code

Output

[
    {'id': 1, 'name': 'Alice'},
    {'id': 2, 'name': 'Bob'},
    {'id': 4, 'name': 'David'}
]

Conclusion

We have learned how to remove a dictionary from a list in Python using list comprehension and the .remove() method with a regular for loop. You can use either of these techniques based on your preference and situation. The main idea is to find the appropriate dictionary based on a condition and remove it from the list.