9

I need to extract those keys of a dictionary whose values pass a certain condition. Basically, I want to do this, only in a shorter, more pythony way:

keys=[]
for key in dict:
    if dict[key]==True:
        keys.append(key)

This was my original idea, but it raises a ValueError:

[key for (key,val) in map if val==True]

I came up with this for the moment, but I can't help feeling it's not very nice:

[key for key in map.keys() if map[key]==True]

Is there a less messy way to it? Perhaps something obvious that I'm clearly missing?

Thanks!

jh314
  • 27,144
  • 16
  • 62
  • 82
purrduc
  • 135
  • 1
  • 5

3 Answers3

5

Here is a way to get the keys with true values that is a lot shorter and cleaner than a comprehension (not that comprehensions are bad though):

>>> dct = {0:False, 1:True, 2:False, 3:True}
>>> list(filter(dct.get, dct))
[1, 3]
>>>
3

Use dict.items()

[key for key, val in dct.items() if val]

If you want to take only the keys with True values, rather than any true-ish value, you can use an equality check:

[key for key, val in dct.items() if val==True]

It is noted in PEP8 though, that one shouldn't compare boolean values using == - so don't use it unless you absolutely need to.

Also, please don't name variables dict or map (even if it's for demonstration purposes only) because they shadow the bulitins.

Volatility
  • 31,232
  • 10
  • 80
  • 89
0

Iterating over a mapping yields only keys. Use map.items() instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358