Home > Software engineering >  Printing only specific values from a dictionary
Printing only specific values from a dictionary

Time:05-30

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.

CodePudding user response:

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

CodePudding user response:

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