python

Remove dictionary from a list in Python

If you are working on a list of dictionaries and want to remove some dictionaries from the list based on the value of the dictionary. You can use the methods listed in this post.

students = [
  {'id': 1, 'name': 'Richard'},
  {'id': 2, 'name': 'Jared'},
  {'id': 3, 'name': 'Dinesh'}
]

for index, item in enumerate(students):
    if item['id'] == 2:
        del students[index]

print(students)
Output
[{'id': 1, 'name': 'Richard'}, {'id': 3, 'name': 'Dinesh'}]

We are using Python For loop and enumerate() function to remove a dictionary from the list based on key 'id' value. 

Get new list after filtering list based on dictionary key-value

Here is another code example to create a new list after removing a dictionary based on some conditions. We are using Python filter() and lambda function to do that.

Code Example

students = [
  {'id': 1, 'name': 'Richard'},
  {'id': 2, 'name': 'Jared'},
  {'id': 3, 'name': 'Dinesh'}
]

result = list(filter(lambda item: item['id'] != 2, students))

print(result)

Output

[{'id': 1, 'name': 'Richard'}, {'id': 3, 'name': 'Dinesh'}]

Use List Comprehension to remove dictionary from a list

We can also use List Comprehension to remove some dictionary items from the list and get a new list with filtered dictionary items.

Code Example

students = [
  {'id': 1, 'name': 'Richard'},
  {'id': 2, 'name': 'Jared'},
  {'id': 3, 'name': 'Dinesh'}
]

result = [item for item in students if not (item['id'] == 2)]

print(result)

Output

[{'id': 1, 'name': 'Richard'}, {'id': 3, 'name': 'Dinesh'}]
Was this helpful?