首页 > 解决方案 > 计算字典中 SPECIFIC/CERTAIN 值的数量

问题描述

我不想计算字典中的值的数量

这是我的代码:

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

为什么会打印 0?既然字典里有绿色,不应该打印1吗?

标签: pythondictionarycount

解决方案


您需要迭代字典的值。目前,您迭代字典中的键,而无需访问值。

请注意,这for i in fav_color是在 Python 中迭代键的惯用方式。

Pythonic 迭代值的方法是使用dict.values

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

实现逻辑的另一种方法是使用sum生成器表达式。这是有效True == 1的,因为 Boolean 是int.

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

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

推荐阅读