简体   繁体   中英

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.

When I use this code, I get 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.

You may use sum on the generator expression to calculate len of each value as:

>>> 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(len, my_dict.values()))
6

You need to sum the lengths of each of the elements in aDict.values() :

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

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