[英]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? 为什么打印0? Since there is a green in the dictionary, shouldn't it print 1?
由于字典中有绿色,所以它不打印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. 请注意,
for i in fav_color
中的for i in fav_color
是在Python中迭代键的一种惯用方式。
The Pythonic way to iterate values is to use dict.values
: Python迭代值的方法是使用
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. 实现逻辑的另一种方法是将
sum
与生成器表达式一起使用。 This works because True == 1
, since Boolean is a subclass of int
. 这是有效的,因为
True == 1
,因为Boolean是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. 您的if语句逻辑没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.