views:

113

answers:

3

I have a dictionary d (and a seperate sorted list of keys, keys). I wanted the loop to only process entries where the value is False - so i tried the following:

for key in keys and not d[key]:
 #do foo

I suppose my understanding of python sytax is not what i thought it was - because the assignment doesnt suppose to have happened above, and a i get an instanciation error.

The below works of course, but I'd really like to be able to use something like the code above.. possible?

for key in keys:
 if d[key]: continue
  #foo time!

Thanks!

+5  A: 

Use a genex for this.

for key in (k for k in keys if not d[k]):
   ....
Ignacio Vazquez-Abrams
From the question, I think that should be ‘if not d[k]‘.
kevingessner
I would discourage doing this because it is not much nicer than the _if cond: continue_, and it doesn't easily allow multiple conditions (In addition you are adding a generator expression for just the "cool" factor... yes you can do it, but it doesn't make the code easier to understand nor does it make it faster (I'd assume it makes it slower))
Terence Honles
Thanks Terence, point taken!
flyingcrab
+2  A: 

If you dict was opposite (True iff the value should be scanned) you could use:

for key in filter(d.get, keys):
    ...
Oren
... and you can extend that to `filter(lambda x: not d[x], keys)` for the False case
Nas Banov
+2  A: 
import itertools as it

for key in it.ifilterfalse(d.get, keys):
   ...

itertools often offers the best ways to pack functionality into iterations (==loops;-).

Alex Martelli
aah, this is cool - itertool has new gifts everyday - thanks Alex!
flyingcrab
@flyingcrab, you're welcome!
Alex Martelli