Python Forum

Full Version: removing dictionary element in list using (key, value)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
# list of dictionary
students = [{'id': '001', 'name': 'John'},
            {'id': '100', 'name': 'Park'},
            {'id': '010', 'name': 'Bjarne'}
           ]

# removing student who's name is Park in students list
def erase_student(key, val):
    for student in students:
        if student[key] == val:
            students.remove(student)

erase_student('name', 'Bjarne')
I want to replace for statement to code like this:
student = student in students if student[key] == value
students.remove(student)
But I can't make proper shorter code.
I'll be thankful if you give me advice.
you should not change list while iterating over it, e.g.
# list of dictionary
students = [{'id': '001', 'name': 'John'},
            {'id': '100', 'name': 'Park'},
            {'id': '002', 'name': 'Bjarne'},
            {'id': '010', 'name': 'Bjarne'}
           ]
 
# removing student who's name is Bjarne in students list
def erase_student(key, val):
    for student in students:
        if student[key] == val:
            students.remove(student)

erase_student('name', 'Bjarne')
print(students)
Output:
[{'id': '001', 'name': 'John'}, {'id': '100', 'name': 'Park'}, {'id': '010', 'name': 'Bjarne'}]
you can do
# list of dictionary
students = [{'id': '001', 'name': 'John'},
            {'id': '100', 'name': 'Park'},
            {'id': '002', 'name': 'Bjarne'},
            {'id': '010', 'name': 'Bjarne'}
           ]
 
# removing student who's name is Bjarne in students list
def erase_student(mylist, key, val):
    return [item for item in mylist if item.get(key) != val]

students = erase_student(students, 'name', 'Bjarne')
print(students)
Output:
[{'id': '001', 'name': 'John'}, {'id': '100', 'name': 'Park'}]
note, it's better to pass the list as argument, rather than rely on global variable and list mutability
# list of dictionary
students = [{'id': '001', 'name': 'John'},
            {'id': '100', 'name': 'Park'},
            {'id': '002', 'name': 'Bjarne'},
            {'id': '010', 'name': 'Bjarne'}
            ]

(students.remove(student) for student in students[:] if student['name'] == 'Bjarne')
print(students)
or
students = [student for student in students if student['name'] != 'Bjarne']
Output:
[{'id': '001', 'name': 'John'}, {'id': '100', 'name': 'Park'}]
I don't like that, because it just rely on side-effect inside list comprehension. It could be generator expression instead.
On line 8 list comprehension is just so that using list mutability to remove elements. I think OP is using remove only because they don't know better