简体   繁体   English

计算字典列表项python

[英]Counting dictionary- list items python

I have a dictionary with the following format 我有一个字典,格式如下

{'bye': ['yellow', 'green', 'orange', 'purple'],
 'hello': ['red'],
 'hi': ['red', 'blue']}

What I'm trying to do is count all the values in this dictionary, no matter what the key is, no matter if the values have the same name, if its there count it. 我正在尝试做的是计算这个字典中的所有值,无论键是什么,无论值是否具有相同的名称,如果它有计数。

So far i have 到目前为止我有

mynumber = 0
for key, value in mydict.iteritems():
  mynumber +=1
return mynumber

This output only give me the total number of keys, what i want is the sum of all values, repeated or not. 这个输出只给出了键的总数,我想要的是所有值的总和,重复与否。 So in this instance mynumber should be 7 所以在这种情况下,mynumber应该是7

您可以将生成器传递给sum()

total = sum(len(item) for item in mydict.itervalues())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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