Python 在字典中搜索值

Python 在字典中搜索值,python,dictionary,count,Python,Dictionary,Count,想在字典里数一数20岁以上的男性人数 我有下面的字典 i={'joe':("male",25), 'fred':("male",39), 'susan':("female",20)} 例如,我知道如何在字典中查找钥匙 print ('joe' in i) 返回true,但 print ('male' in i.values()) print ('male in i) 两者都返回false。我怎样才能让它返回真值 最终,我试图在字典中计算某个年龄段的男性人数你可以使用一个insum: i={

想在字典里数一数20岁以上的男性人数

我有下面的字典

i={'joe':("male",25), 'fred':("male",39), 'susan':("female",20)}
例如,我知道如何在字典中查找钥匙

print ('joe' in i)
返回true,但

print ('male' in i.values())
print ('male in i)
两者都返回false。我怎样才能让它返回真值 最终,我试图在字典中计算某个年龄段的男性人数

你可以使用一个in
sum

i={'joe':("male",25), 'fred':("male",39), 'susan':("female",20)}
In [1]: dictionary = {'joe':("male",25), 'fred':("male",39), 'susan':("female",20)}
In [2]: sum(gender=='male' for gender, age in dictionary.values() if age > 20)
Out[2]: 2
条件
gender==“male”
将导致
True
False
,并将其评估为1或0。这将使得通过汇总最终结果来计算有效条件成为可能

    i={'joe':("male",25), 'fred':("male",39), 'susan':("female",20)}

    'joe' in i 
    equals
    'joe' in i.keys()

where i.keys() == ['joe', 'fred', 'susan']
现在,

这里,每个元素(例如('female',20)都是一个元组,您试图将其与一个字符串进行比较,该字符串将给出false

So when you do 
print ('male' in i.values()) -> returns false

print ('male in i) -> 'male' not in i.keys()
解决办法如下:

sum(x=='male' and y > 20 for x, y in i.values())

or

count = 0
for x, y in i.values():
    if x == 'male' and y > 20:
        count += 1
print(count)

您可以使用
.iter()
函数迭代dict中的键和值。然后,您可以检查0索引中的“男性”值和1索引中的年龄值

count = 0
for key, value in i.iter():
    if value[0] == "male" and value[1] > 20:
        count += 1

给出值中包含“joe”的所有键的列表。

谢谢-然后我如何检查男性是否介于特定的ages@chrischris只需在表达式的末尾添加条件。
keys = [x for x, y in token.items() if "joe" in y]