简体   繁体   中英

Counting first element in python and printing?

I have a data structure in Python that keeps track of client analytics that looks like this

'B': ['J'], 'C': ['K'], 'A': ['L'], 'D': ['J'], 'E': ['L']

I'm trying to print a table like this:

Site Counts:
    J  got  2 hits
    K  got  1 hits
    L  got  2 hits

So far I've thought of using the .fromkeys() method, but don't have too much of an idea as to how to go about getting the data, I've tried a lot of different things and have had no luck on this problem.

Python comes with a counter class included: collections.Counter() :

from collections import Counter

site_counts = Counter(value[0] for value in inputdict.values())

Demo:

>>> from 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] for value in inputdict.values())
>>> site_counts
Counter({'J': 2, 'L': 2, 'K': 1})

Counter is a dictionary sub-class, so you could just loop over the keys now and print out the counts associated, but you could also have the output sorted by count (descending) by using the Counter.most_common() method :

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

which for your sample input prints:

Site Counts:
    J  got  2 hits
    L  got  2 hits
    K  got  1 hits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM