Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching dictionary for values

Looking to count the number of males in a dictionary over the age of 20.

I have the following dictionary

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

i know how to search the dictionary for a key for example

print ('joe' in i)

returns true but

print ('male' in i.values())
print ('male in i)

both return false. how can i get it to return true Ultimately i am trying to count the number of males over a certain age in the dictionary

like image 845
chrischris Avatar asked Dec 07 '25 15:12

chrischris


1 Answers

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

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

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

Now,

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

here, each element for example ('female', 20) is a tuple and you are trying to compare it with a string which will give you false.

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

print ('male in i) -> 'male' not in i.keys()

Solution would be as follows:

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)
like image 113
JkShaw Avatar answered Dec 09 '25 06:12

JkShaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!