Python count items in dict value that is a list

RolfBly picture RolfBly · May 31, 2013 · Viewed 57.2k times · Source

Python 3.3, a dictionary with key-value pairs in this form.

d = {'T1': ['eggs', 'bacon', 'sausage']}

The values are lists of variable length, and I need to iterate over the list items. This works:

count = 0
for l in d.values():
   for i in l: count += 1

But it's ugly. There must be a more Pythonic way, but I can't seem to find it.

len(d.values()) 

produces 1. It's 1 list (DUH). Attempts with Counter from here give 'unhashable type' errors.

Answer

Martijn Pieters picture Martijn Pieters · May 31, 2013

Use sum() and the lengths of each of the dictionary values:

count = sum(len(v) for v in d.itervalues())

If you are using Python 3, then just use d.values().

Quick demo with your input sample and one of mine:

>>> d = {'T1': ['eggs', 'bacon', 'sausage']}
>>> sum(len(v) for v in d.itervalues())
3
>>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
>>> sum(len(v) for v in d.itervalues())
7

A Counter won't help you much here, you are not creating a count per entry, you are calculating the total length of all your values.