Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dictionary by value then key

I can sort by key or value, but I need it sorted by value, then key, in one line. To explain this better I can show you my problem:

dict = {'apple': 2, 'banana': 3, 'almond':2 , 'beetroot': 3, 'peach': 4} 

I want my output to be sorted descending by their value and then ascending (A-Z) by their key (alphabetically). Resulting in such a list:

With the output of: ['peach', 'banana', 'beetroot', 'almond', 'apple']

The only way I know how to do it so far is:

[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k))] 

With the output of: ['almond', 'apple', 'banana', 'beetroot', 'peach']

So it has sorted the values in ascending order and the keys alphabetically in ascending order (A-Z). So if I reverse this:

[v[0] for v in sorted(dict.items(), key=lambda(k,v): (v,k), reverse=True)] 

With the output of: ['peach', 'beetroot', 'banana', 'apple', 'almond']

It has sorted the values in descending order and the keys alphabetically in descending order (Z-A).

Is there a way I can sort the values in descending order and the keys in ascending order (i.e. A-Z) and get the output I showed above?

like image 996
tcatchy Avatar asked Mar 29 '12 05:03

tcatchy


People also ask

How do you sort a dictionary by value then key?

The key=lambda x: (x[1],x[0]) tells sorted that for each item x in y. items() , use (x[1],x[0]) as the proxy value to be sorted. Since x is of the form (key,value) , (x[1],x[0]) yields (value,key) . This causes sorted to sort by value first, then by key for tie-breakers.

How do you sort a dictionary based on a value and a key in Python?

First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.

Can we sort a dictionary with keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.

How do you sort dictionaries by dictionary value?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.


1 Answers

You need to take advantage of the fact that the values are numbers.

>>> [v[0] for v in sorted(d.iteritems(), key=lambda(k, v): (-v, k))] ['peach', 'banana', 'beetroot', 'almond', 'apple'] 
like image 105
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 08:09

Ignacio Vazquez-Abrams