python - How to count size of lists with a dict? -


if have dict of lists like:

{     'id1': ['a', 'b', 'c'],     'id2': ['a', 'b'],     # etc. } 

and want tally size of lists, i.e.. number of ids >0, >1, >2...etc

is there easier way nested loops this:

dictofoutputs = {} x in range(1,11):     count = 0     agentid in useriddict:         if len(useriddict[agentid]) > x:             count += 1     dictofoutputs[x] = count         return dictofoutputs 

i'd use collections.counter() object collect lengths, accumulate sums:

from collections import counter  lengths = counter(len(v) v in useriddict.values()) total = 0 accumulated = {} length in range(max(lengths), -1, -1):     count = lengths.get(length, 0)     total += count     accumulated[length] = total 

so collects counts each length, builds dictionary accumulative lengths. o(n) algorithm; loop on values once, add on smaller straight loops (for max() , accumulation loop):

>>> collections import counter >>> import random >>> testdata = {''.join(random.choice('abcdefghijklmnopqrstuvwxyz') _ in range(5)): [none] * random.randint(1, 10) _ in range(100)} >>> lengths = counter(len(v) v in testdata.values()) >>> lengths counter({8: 14, 7: 13, 2: 11, 3: 10, 4: 9, 5: 9, 9: 9, 10: 9, 1: 8, 6: 8}) >>> total = 0 >>> accumulated = {} >>> length in range(max(lengths), -1, -1): ...     count = lengths.get(length, 0) ...     total += count ...     accumulated[length] = total ...  >>> accumulated {0: 100, 1: 100, 2: 92, 3: 81, 4: 71, 5: 62, 6: 53, 7: 45, 8: 32, 9: 18, 10: 9} 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -