3

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
4
  • 1
    Counter depends on dict which depends on unsorted hashtable. Commented Feb 7, 2017 at 14:54
  • 3
    What you see in the Counter's repr is the counter's internal dictionary, which is not ordered. If you want the contents in sorted order, try Counter.most_common Commented Feb 7, 2017 at 14:54
  • What is the order you expect? First appeared, max occurrences, min occurrences, key? Commented Feb 7, 2017 at 14:55
  • max to min 2262, 2262, 72,44, 10 , 10 , 10, 10 Commented Feb 7, 2017 at 14:55

3 Answers 3

6

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Or just Counter.most_common? Can also take a parameter, e.g. most_common(10) for top-ten elements.
@tobias_k indeed, totally forgot about most_common returning ordered list of tuples. thanks
2

use counter.most_common():

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

Comments

0

What you have in your Counter object is a dict. The order is not random but:

Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

You could solve this with the use of an orderddict.

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.