2017-04-22 157 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