Python3: Conditional extraction of keys from a dictionary with comprehension
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]>>>
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.
Iterating over a mapping yields only keys. Use map.items()
instead.