Sort a counter based, re-organize based on frequency, in Python

234 Views Asked by At

My code looks like this:

with open('toy_two.json', 'rb') as inpt:

    dict_hash_gas = list()
    for line in inpt:
        resource = json.loads(line)
        dict_hash_gas.append({resource['first']:resource['second']})

# Count up the values
counts = collections.Counter(v for d in dict_hash_gas for v in d.values())

# Apply a threshold
counts = {k:v for k,v in counts.iteritems() if v > 1}

print(counts)

Here is the data:

{"first":"A","second":"1","third":"2"} 
{"first":"B","second":"1","third":"2"} 
{"first":"C","second":"2","third":"2"} 
{"first":"D","second":"3","third":"2"} 
{"first":"E","second":"3","third":"2"} 
{"first":"F","second":"3","third":"2"} 
{"first":"G","second":"3","third":"2"} 
{"first":"H","second":"4","third":"2"} 
{"first":"I","second":"4","third":"2"} 
{"first":"J","second":"0","third":"2"} 
{"first":"K","second":"0","third":"2"} 
{"first":"L","second":"0","third":"2"} 
{"first":"M","second":"0","third":"2"} 
{"first":"N","second":"0","third":"2"} 

The corresponding output:

{u'1': 2, u'0': 5, u'3': 4, u'4': 2}

What I'd like to do is sort this output, so that it's rendered as:

{ u'0': 5, u'3': 4, u'4': 2, u'1': 2}

Thus far I tried counts = counts.most_common(), but it didn't work. I got the following error:

AttributeError: 'dict' object has no attribute 'most_common'
1

There are 1 best solutions below

4
On BEST ANSWER
# Count up the values
counts = collections.Counter(v for d in dict_hash_gas for v in d.values())

counts is a Counter instance, which understands most_common method.

# Apply a threshold
counts = {k:v for k,v in counts.iteritems() if v > 1}

counts is now a dict, which doesn't understand most_common.

You just need to apply most_common first, and then apply the treshold:

data = [{"first":"A","second":"1","third":"2"} ,
    {"first":"B","second":"1","third":"2"} ,
    {"first":"C","second":"2","third":"2"} ,
    {"first":"D","second":"3","third":"2"} ,
    {"first":"E","second":"3","third":"2"} ,
    {"first":"F","second":"3","third":"2"} ,
    {"first":"G","second":"3","third":"2"} ,
    {"first":"H","second":"4","third":"2"} ,
    {"first":"I","second":"4","third":"2"} ,
    {"first":"J","second":"0","third":"2"} ,
    {"first":"K","second":"0","third":"2"} ,
    {"first":"L","second":"0","third":"2"} ,
    {"first":"M","second":"0","third":"2"} ,
    {"first":"N","second":"0","third":"2"}]

from collections import Counter
c = Counter(int(d["second"]) for d in data)
print(c)
# Counter({0: 5, 3: 4, 1: 2, 4: 2, 2: 1})
print(c.most_common())
# [(0, 5), (3, 4), (1, 2), (4, 2), (2, 1)]
print([(value, count) for value, count in c.most_common() if count > 1])
# [(0, 5), (3, 4), (1, 2), (4, 2)]