pythonloopsdictionaryfilter

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.


Solution

  • This should do it:

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

    Output:

    candidate 1 candidate 4