Counting first element in python and printing? -


i have data structure in python keeps track of client analytics looks this

'b': ['j'], 'c': ['k'], 'a': ['l'], 'd': ['j'], 'e': ['l'] 

i'm trying print table this:

site counts:     j  got  2 hits     k  got  1 hits     l  got  2 hits 

so far i've thought of using .fromkeys() method, don't have of idea how go getting data, i've tried lot of different things , have had no luck on problem.

python comes counter class included: collections.counter():

from collections import counter  site_counts = counter(value[0] value in inputdict.values()) 

demo:

>>> collections import counter >>> inputdict = {'b': ['j', 'k', 'l'], 'c': ['k', 'j', 'l'], 'a': ['l', 'k', 'j'], 'd': ['j', 'l', 'k'], 'e': ['l', 'j', 'k']} >>> site_counts = counter(value[0] value in inputdict.values()) >>> site_counts counter({'j': 2, 'l': 2, 'k': 1}) 

counter dictionary sub-class, loop on keys , print out counts associated, have output sorted count (descending) using counter.most_common() method:

print('site counts:') site, count in site_counts.most_common():     print('    {}  got {:2d} hits'.format(site, count)) 

which sample input prints:

site counts:     j  got  2 hits     l  got  2 hits     k  got  1 hits 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -