alex23 wrote:
On Jan 22, 1:16 am, TP <tribulati...@paralleles.invalid> wrote:
Is the following code pythonic:
l=[{"title":"to", "value":2},{"title":"ti","value":"coucou"}]
dict = [ dict for dict in l if dict['title']=='ti']
l.remove(*dict)
l
[{'title': 'to', 'value': 2}]
Try not to use 'dict' or the name of any of the other built-in types
as labels.
You're stepping through an entire list just to pass another list to
l.remove to step through and remove items from...in fact, given that
list.remove deletes the -first- occurance of the item, you're asking
it to loop through -again- to find the matching element which you've -
already- detected. A better and cleaner approach would be to step
through the list -once- and remove the item when you find it:
for index, record in enumerate(l):
if record['title'] == 'ti':
l.pop(index)
[snip]
FYI, you shouldn't modify a list you're iterating over.
Or you could just use a list comprehension:
l = [d for d in l if d['title'] == 'ti']
The for-loop was removing the item where there's a match, so the list
comprehension in this case should keep the item where there _isn't_ a match:
l = [d for d in l if d['title'] != 'ti']
[remainder snipped]
--
http://mail.python.org/mailman/listinfo/python-list