Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in python for loop possible?

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!

like image 442
malangi Avatar asked Jul 14 '26 20:07

malangi


2 Answers

Use a genex for this.

for key in (k for k in keys if not d[k]):
   ....
like image 145
Ignacio Vazquez-Abrams Avatar answered Jul 16 '26 09:07

Ignacio Vazquez-Abrams


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

for key in filter(d.get, keys):
    ...
like image 39
Oren Avatar answered Jul 16 '26 08:07

Oren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!