If you want a one liner, you could use a generator expression with next()
, which short-circuits once you've found the first item to remove, and then use list.remove()
:
l.remove(next(d for d in l if d['name'] == value))
Example:
>>> l = [{'name':'bob','age':12},{'name':'jill','age':34}]
>>> value = 'bob'
>>> l.remove(next(d for d in l if d['name'] == value))
>>> l
[{'name': 'jill', 'age': 34}]
Note this will raise a StopIteration
is the value
is not found, which can be avoided, but it's a bit longer because although next()
has a default argument, list.remove()
does not:
>>> l = [{'name':'bob','age':12},{'name':'jill','age':34}]
>>> value = 'bob'
>>> value_to_remove = next((d for d in l if d['name'] == value), None)
>>> 'Value not in list' if value_to_remove is None else l.remove(value_to_remove)
>>> l
[{'name': 'jill', 'age': 34}]
>>> value_to_remove = next((d for d in l if d['name'] == value), None)
>>> 'Value not in list' if value_to_remove is None else l.remove(value_to_remove)
'Value not in list'