andy boot
andy boot

Reputation: 11727

Python deleting from a dictionary using list comprehensions

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

Answers (5)

xSabotagex
xSabotagex

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

aknuds1
aknuds1

Reputation: 67987

  1. You're not gaining anything from the list comprehension here, because you're not after a new list.
  2. del isn't a function, so you can't invoke it as part of a list comprehension.

Basically, just iterate over the list instead:

for r in to_remove:
    del my_dict[r]

Upvotes: 5

Aesthete
Aesthete

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

Zaur Nasibov
Zaur Nasibov

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

jamylak
jamylak

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

Related Questions