[CentralOH] Counting array sizes

Eric Floehr eric at intellovations.com
Thu Mar 26 01:55:25 CET 2015


I had a dictionary indexed by strings, with the value being an array of one
or more items. I wanted to know how many had 1 item, how many had 2, etc.

My solution was to use Counter from collections:

>>> from collections import Counter
>>> d = { 'A': [1], 'B': [2,3], 'C': [4], 'D': [1,2,3]}
>>> lens = [ len(value) for value in d.values() ]
>>> print(lens)
[1, 1, 2, 3]
>>> counts = Counter(lens)
>>> print(counts)
Counter({1: 2, 2: 1, 3: 1})
>>> counts[1]
2

In my case it was a dictionary of 850 entries, with arrays of varying size.
It made understanding the composition of the the dictionary easier.

What Python module/class/function has made your life easier?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20150325/4e4e745d/attachment.html>


More information about the CentralOH mailing list