Sort dictionary by values ​​in python

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

Is it possible to sort a dictionary by values?

I want to be able to take the 10 most popular words in my dictionary. Values ​​represent the number of words, and 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 still have, but it is only the print of the first 10 points in the dictionary. How do I print the 10 most popular items? (i.e. the values ​​with the highest int value as the value?)

+4
source share
5 answers

The Python dictionary is unordered, but you can convert it to a list of tuples with items() and pass the corresponding comparison function to the sort key parameter.

sorted() has a similar key parameter. You want to sort by lambda item: item[1] to get the value from items() and iteritems() . Then you can simply cut off the first N elements.

So...

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

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

+2
source

Use

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

or

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

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

+2
source

You cannot sort dicts at all. They are disordered, i.e. The order is undefined and completely meaningless (for you).

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

+1
source

To do this, you must sort it using the key argument. key should be a function that takes an element as input and returns another that should be sortable, and will sort all elements using this key. And take the last 10 items (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) 
0
source

Source: https://habr.com/ru/post/1347958/


All Articles