raspberry rick
raspberry rick

Reputation: 33

Counting the number of SPECIFIC/CERTAIN values in dictionary

I am not trying to count the number of values in the dictionary

Here's my code:

def use_favcolors(fav_color):
    count = 0
    for green in fav_color:
        if green == fav_color:
            count += 1
    print count

def main():
    use_favcolors({"John": "green", "Bobby": "blue", "PapaSanta": "yellow"})
main()

Why does this print 0? Since there is a green in the dictionary, shouldn't it print 1?

Upvotes: 2

Views: 67

Answers (2)

jpp
jpp

Reputation: 164613

You need to iterate the values of your dictionary. Currently, you iterate the keys in the dictionary, without ever accessing values.

Note that for i in fav_color is an idiomatic way of iterating keys in Python.

The Pythonic way to iterate values is to use dict.values:

def use_favcolors(fav_color):
    count = 0
    for color in fav_color.values():
        if color == 'green':
            count += 1
    print count

Another way you can implement your logic is to use sum with a generator expression. This works because True == 1, since Boolean is a subclass of int.

d = {"John": "green", "Bobby": "blue", "PapaSanta": "yellow"}

res = sum(i=='green' for i in d.values())  # 1

Upvotes: 2

John Salami
John Salami

Reputation: 36

def use_favcolors(fav_color):
    count = 0
    for i in fav_color:
         if fav_color[i] == "green":
         count += 1
    print(count)

def main():
    use_favcolors({"John": "green", "Bobby": "blue", "PapaSanta": "yellow"})
main()

Your if statement logic did not make sense.

Upvotes: 1

Related Questions