brianpb245 brianpb245 - 1 year ago 73
Python Question

Python Sort Counter

I cannot get my counter to sort/displayed properly

My code is

with open('nonweb') as f:
for i in f:
entry.append(i.strip())
counter=Counter(entry)
print counter

for z in counter:
print '%s : %d' % (z, counter[z])


counter is

Counter({'192.168.1.45 UDP 137': 2262, '192.168.1.85 UDP 137': 2262, '192.119.43.56 UDP 53': 78, '192.119.39.68 UDP 53': 78, '192.168.92.223 UDP 10111': 78, '192.168.1.13 UDP 137': 72, '192.167.80.106 TCP 8087': 48, '192.168.1.127 UDP 8083': 48, '192.168.1.129 UDP 8083': 44, '192.218.30.124 UDP 53': 32, '192.77.58.44 TCP 5282': 24, '192.168.1.13 UDP 138': 18, '192.168.1.69 UDP 138': 14, '192.168.1.85 UDP 138': 10, '192.168.1.57 UDP 138': 10, '192.168.1.33 UDP 138': 10, '192.168.1.45 UDP 138': 10, '192.168.1.92 UDP 138': 10, '192.168.1.97 UDP 138': 10, '192.168.1.79 UDP 138': 10, '192.168.1.60 UDP 138': 10, '192.168.1.32 UDP 138': 10, '192.168.1.18 UDP 138': 10, '192.168.1.58 UDP 138': 10, '192.168.1.95 UDP 138': 10, '192.168.1.19 UDP 138': 10, '192.168.1.143 UDP 138': 10, '192.168.1.138 UDP 138': 10, '192.168.1.99 UDP 138': 10, '192.168.1.139 UDP 138': 10, '192.168.1.96 UDP 138': 10, '192.168.1.140 UDP 138': 10, '192.168.1.137 UDP 138': 10, '192.168.1.59 UDP 138': 10, '192.171.70.154 UDP 53': 6, '216.163.251.236 TCP 42590': 2, '192.168.1.140 TCP 56230': 2})


but when i try to display it in a presentable format, it does not print in the same order as the counter list. ( preferably no semi:colon)

192.168.1.45 UDP 137 : 2262
192.168.1.85 UDP 137 : 2262
192.168.1.85 UDP 138 : 10
192.168.1.57 UDP 138 : 10
192.168.1.33 UDP 138 : 10
192.168.1.45 UDP 138 : 10
192.168.1.92 UDP 138 : 10
192.168.1.129 UDP 8083 : 44
192.168.1.97 UDP 138 : 10
192.168.1.13 UDP 137 : 72
192.168.1.79 UDP 138 : 10

Answer Source

Since Counter is implemented as a dictionary it doesn't really have a sense of order. If you want to manually iterate over its elements by order you will need to create such order:

# reverse=True to get descending order
for k, v in sorted(counter_obj.items(), key=lambda x: x[1], reverse=True):
    print(k, v)

Or simply iterate over the list of tuples returned by the most_common method as suggested by @tobias_k in the comments:

for k, v in c.most_common():
    print(k, v)

Interesting to note that most_common is implemented in almost the exact way:

def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        >>> Counter('abcdeabcdabcaba').most_common(3)
        [('a', 5), ('b', 4), ('c', 3)]

        '''
        # Emulate Bag.sortedByCount from Smalltalk
        if n is None:
            return sorted(self.items(), key=_itemgetter(1), reverse=True)
        return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download