简体   繁体   中英

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?

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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM