Sort python dict values ​​with sorted built-in function

I need to get a sorted dict view sorted in descending order of values ​​(the largest value in the dict should be shown first).

Example:

mydict={u'jon':30,u'den':26,u'rob':42,u'jaime':31} 

I need to show them how

 rob=42 jaime=31 jon=30 den=28 

I tried this

 from operator import itemgetter sortedvalues=sorted(mydict,key=itemgetter(1)) 

When I print a list, I get

 [u'jaime', u'den', u'rob', u'jon'] 

This list is unordered! Am I missing something due to using sorted inline? or am I using itemgetter incorrectly?

+6
source share
3 answers

This is an interesting problem, because you did not cause an error, as if you had keys to another non-indexable type (say, integers), and this is due to a thin series of things:

  • sorted (mydict, ...) tries to iterate the dictionary using the equivalent of iter(mydict) , which will call mydict.__iter__()
  • An iteration of the dictionary gives its keys ; in reality, iter(mydict) matches mydict.iterkeys() .
  • Your keys were strings, and since the strings are indexed, itemgetter(1) will work with the string value, getting the second character in the string.

The code you had with an IndexError error, if any lines had a length of 1 char, you were just lucky. (or not, depending on how you look at it, since getting an IndexError might help you understand the problem earlier).

What do you want to do if you want only the values:

 sorted(mydict.values(), reverse=True) 

And if you want the keys to hit too, you want

 sorted(mydict.iteritems(), key=itemgetter(1), reverse=True) 
+11
source

They are sorted by the second letter in the name; iteration by type gives its keys.

 sorteditems = sorted(mydict.iteritems(), key=itemgetter(1)) 
+5
source

A dictionary iteration (which the sorted function sorted ) will give you only its keys:

 >>> sorted(mydict) [u'den', u'jaime', u'jon', u'rob'] 

Instead, you want to sort both keys and values ​​- for this you should use mydict.items() (or mydict.iteritems() , which is more efficient with large dicts):

 >>> sorted(mydict.items()) [(u'den', 26), (u'jaime', 31), (u'jon', 30), (u'rob', 42)] 

Then your code will work as expected:

 >>> from operator import itemgetter >>> sorted(mydict.items(), key = itemgetter(1)) [(u'den', 26), (u'jon', 30), (u'jaime', 31), (u'rob', 42)] 

You can also sort using the dict key as a secondary sort value if multiple keys have the same value:

 >>> mydict={u'a': 1, 'z': 1, 'd': 1} >>> sorted(mydict.items(), key = itemgetter(1)) [(u'a', 1), ('z', 1), ('d', 1)] >>> sorted(mydict.items(), key = itemgetter(1, 0)) [(u'a', 1), ('d', 1), ('z', 1)] 
+3
source

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


All Articles