[CentralOH] Counting array sizes

Peter Carswell pcarswell.1 at gmail.com
Mon Mar 30 18:34:57 CEST 2015


I have use exercises with dictionaries which required the get() method
...especially the feature which when the particular key was not found, a
dictionary element was created with a specified value.

""" Returning home next meet-up. """
pete

On Wed, Mar 25, 2015 at 8:55 PM, Eric Floehr <eric at intellovations.com>
wrote:

> 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?
>
>
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> https://mail.python.org/mailman/listinfo/centraloh
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20150330/63dfa286/attachment.html>


More information about the CentralOH mailing list