简体   繁体   English

计算字典中的值数

[英]Counting the number of values in a dictionary

I need to write a program that counts the number of values in a dictionary. 我需要编写一个程序来计算字典中值的数量。

For example, say I have this dictionary. 例如,说我有这本字典。

{'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}

I should get 6 as a result, because there's 6 values. 结果应该是6,因为有6个值。

When I use this code, I get 4. 当我使用此代码时,我得到4。

def how_many(aDict):

    sum = len(aDict.values())

    return sum

animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}

print(how_many(animals))

I'm very new to Python so please don't do anything to hard. 我是Python的新手,所以请不要做任何困难的事情。

You may use sum on the generator expression to calculate len of each value as: 您可以在生成器表达式上使用sum来计算每个值的len ,如下所示:

>>> my_dict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}

#       returns list of all values v
>>> sum(len(v) for v in my_dict.values())
6

Alternatively , you may also use map with sum to achieve this as: 或者 ,您也可以使用带有sum map来实现此目的:

>>> sum(map(len, my_dict.values()))
6

You need to sum the lengths of each of the elements in aDict.values() : 您需要对aDict.values()中每个元素的长度求和:

>>> aDict = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
>>> sum(len(item) for item in aDict.values())
6

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

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