Ignas Kiela
Ignas Kiela

Reputation: 180

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 False?

Upvotes: 4

Views: 5243

Answers (4)

Aaditya Ura
Aaditya Ura

Reputation: 12669

Simple solution of your problem :

for i,j in my_dict.items():
    if j is False:
        print(i)

Additional information :

In python we can use if something: for checking truthy and falsy :

so :

for i,j in my_dict.items():

    if not j:
        print(i)

You can use generator expression :

print(list((key for key,value in my_dict.items() if not value)))

Upvotes: 1

Tabaene Haque
Tabaene Haque

Reputation: 574

You can do something like this:

>>> my_dict={'val1':True,'val2':False,'val3':False,'val4':True}
>>> [k for k, v in my_dict.items() if not v]
['val2', 'val3']
>>> 

Upvotes: 1

eugecm
eugecm

Reputation: 1249

You have to filter them first, this is a working example:

for key in (k for k, v in my_dict.items() if not v):
    print(key)

This works by going through all the (key, value) pairs, and iterating over the keys that have a negative value

Upvotes: 0

Kaushik NP
Kaushik NP

Reputation: 6781

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']

Upvotes: 6

Related Questions