Reputation: 11727
I'm trying to be a good pythonista and use list comprehensions where possible...
Why doesn't this work?
[del my_dict[r] for r in to_remove]
The goal is to remove the entries in the list to_remove
from my dict object my_dict
This:
for r in to_remove:
del my_dict[r]
works fine but I am trying to do it with list comprehensions
Upvotes: 5
Views: 4978
Reputation: 93
You COULD do:
[my_dict.pop(r) for r in to_remove]
.pop
returns the value of the deleted key tho and it would be a tiny bit slower than del
(see here) and not the most "pythonic" way to do this. So you probably shouldn't as others have advised.
Upvotes: 1
Reputation: 67987
Basically, just iterate over the list instead:
for r in to_remove:
del my_dict[r]
Upvotes: 5
Reputation: 18850
You could do this, but I'd listen to jamylak. And of course this is returning a new list, not removing from my_dict
my_dict = [x for x in my_dict if x not in to_remove]
Upvotes: 0
Reputation: 22659
Because del X
is a statement that is not meant to be used like that. It is syntactically incorrect.
Just:
for r in to_remove:
del my_dict[r]
Upvotes: 12
Reputation: 133494
You shouldn't be using a list comprehensions for side effects, it's not pythonic.
A simple for loop should be used instead.
Upvotes: 16