ignasas kielasas ignasas kielasas - 3 years ago 247
Python Question

Iterate through dict key with a specific value

I have a dict like this:

my_dict={val1:True, val2:False, val3:False, val4:True}

How do I iterate through this dict's keys that have value

Answer Source

Just use List comprehension :

[key for key,val in my_dict.items() if val==False]

This will return a list containing the keys that have value as False . Now, it is a simple matter of going through the list.

#driver values :

IN : my_dict = {'a': True,'b': False, 'c': True, 'd': False}
OUT : ['b','d']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download