1

I have a dictionary where each keys have multiple values. I am trying to count the total number of values. For example:

key: 1, value: abc, bcd, egf
key: 2, value: asj,asfah,afhs,jhsafh

so, the total number of values are 3+4 = 7 What is the pythonic way to get this count. Thanks

3
  • Good Q: to answerers, what's gonna happen if len doesnt work in some items? Commented Nov 1, 2011 at 20:51
  • @yosukesabai I think the answers' assumption that the values are sequences is reasonable. The general solution for iterables would be sum(1 for value in value_iterable), and there are several ways you could check if the item was iterable or not, if you could have a list that was that heterogeneous (you shouldn't). Commented Nov 1, 2011 at 21:02
  • @agf: Thanks, I often got screwed up like dct['k'] = "wrong", instead of dct['k'] = ["correct"]. guess it is a matter of discipline. Commented Nov 1, 2011 at 21:06

3 Answers 3

7

How about:

sum(len(val) for val in dictionary.itervalues())

Note that this uses a generator instead of creating a temporary list of lengths.

Sign up to request clarification or add additional context in comments.

Comments

4

You'll want to iterate through all the keys and values in the dictionary, finding the length of each set of values.

The following does uses a list comprehension to build a list of all these lengths, and then takes their sum:

sum([len(value) for key, value in my_dict.iteritems()]) 

If you want to be more efficient, you can replace for key, value in my_dict.iteritems() with for value in my_dict.itervalues() and a use generator expression as suggested by Cameron.

2 Comments

Don't need the keys so itervalues is better than iteritems and don't need all the lens at once so a generator expression is better than a list comprehension.
Definitely the case. I would revise it, but Cameron definitely had a faster gun, so he can have the credit.
2

If you're sure that each value in the dict will be a list, then this works:

sum(len(val) for val in d.itervalues())

If not, a bit more care is required, and probably a bit more info. Strings, for example, also have a len (the count of characters in the string). You probably want strings to count as 1 entry, rather than a count proportional to length. If so, this less readable version works:

sum(1 if isinstance(val, basestring) else len(val) for val in d.itervalues())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.