2017-04-22 153 views
1

展望的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。我怎样才能得到它返回true 最终我试图计算男性人数超过一定年龄的字典中的

回答

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

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

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

现在,

i.values() 
[('female', 20), ('male', 25), ('male', 39)] 

这里,例如每个元素(“女”,20)是一个元组,而您试图将其与一个字符串,它会给你假的比较。

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) 
1

您可以在sum用生成器表达式:

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.这样可以通过总结最终结果来计算有效条件。

+0

谢谢 - 我怎么会那么检查的男性有一定的年龄段之间 – chrischris

+0

@chrischris就在表达式的末尾添加条件。 – Kasramvd

1

您可以通过键和值迭代的字典使用.iter()功能。然后你可以检查“男性”的0指数和年龄的1指数。

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