Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing only specific values from a dictionary

I have a Python dictionary , with 400 elements in it. They are of the form :

{'candidate 1' : 1, 'candidate 2' : 0, 'candidate 3' :0, 'candidate 4' :1}

and so on for about 400 values, I want to print the candidate id whose values in the dictionary are 1. The value takes either 0 (absent) or 1 (present).

I tried using dict.values() function and tried to loop it around and print only the value where dict.value == 1. But it’s only printing the first value and not iterating over.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a loop to print

d = {'candidate 1' : 1, 'candidate 2' : 0, 'candidate 3' :0, 'candidate 4' :1}
for k,v in d.items():
    if v == 1:
        print(k)
        
# candidate 1
# candidate 4

Use a comprehension to get a list

[k for k,v in d.items() if v==1]
# ['candidate 1', 'candidate 4']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading