Tom
Tom

Reputation: 215

Sorting dictionary by values in python

I have a dictionary with key as words and values as ints.

Is it possible to sort the dictionary by values?

I want to be able to take the top 10 most occurring words in my dictionary. The values represent the word counts and the keys represent the word.

counter = 9
for a,b in sorted(dict_.iteritems()):
        if counter > 0:
            print str(a),str(b)+"\n"
            counter-=1

This is what i have so far but it is only printing off the first 10 items in the dictionary. How would I print off the top 10 most frequent items? (ie The values with the highest int as the value?)

Upvotes: 4

Views: 13642

Answers (5)

nmichaels
nmichaels

Reputation: 51029

Python dictionaries are unordered, but you can convert it to a list of tuples using items() and pass an appropriate comparison function to sort's key parameter.

sorted() has an analogous key parameter. You'd want to sort by lambda item: item[1] to get the value out of items() and iteritems(). Then you can just slice off the first N items.

So...

for a, b in sorted(dict_.iteritems(), key=lambda item: item[1], reverse=True)[:10]:
    print a, b

Upvotes: 2

Alexander Gessler
Alexander Gessler

Reputation: 46677

Use

sorted(dict_.iteritems(), key=lambda x:x[1]) 

or

import operator
sorted(.... key=operator.itemgetter(1)) 

to sort based on element values. You can use the reverse=True argument to invert the order of the results (default oder is ascending values) and slice notation (results[:10]) to iterate only the first 10 elements. You can also omit the reverse flag and use [-10:] to get the top 10.

Upvotes: 2

Santiago Alessandri
Santiago Alessandri

Reputation: 6855

In order to do that you should sort it using the key argument. key must be a function that takes an element as input and returns another that should be sortable and it will sort the whole elements using this key. And take the last 10 elements (it is sorted in ascending order). In your case you will need to do something like this:

for a,b in sorted(key=lambda x: (x[1], x[0]), dict_.iteritems())[-10:]:
    print str(a), str(b)

Upvotes: 0

user395760
user395760

Reputation:

You can't sort dicts at all. They're unordered, i.e. the order is undefined and completely meaningless (for you).

However, you can sort .iteritems() with key=operator.itemgetter(1) (other answers negate the value, but you can just use the slice [-10:] to get the last 10 items). Or, in this particular case, just use collections.Counter, which comes with a .most_common(n) method.

Upvotes: 1

Walter Mundt
Walter Mundt

Reputation: 25271

Try sorted(dict_.iteritems(), key=lambda item: -item[1]).

Upvotes: 2

Related Questions