简体   繁体   English

仅打印字典中的特定值

[英]Printing only specific values from a dictionary

I have a Python dictionary , with 400 elements in it.我有一个 Python 字典,里面有 400 个元素。 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).依此类推,对于大约 400 个值,我想打印字典中值为 1 的候选 id。该值取 0(不存在)或 1(存在)。

I tried using dict.values() function and tried to loop it around and print only the value where dict.value == 1 .我尝试使用dict.values()函数并尝试循环它并仅打印dict.value == 1的值。 But it's only printing the first value and not iterating over.但它只打印第一个值而不是迭代。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM