Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/66051855/python-sort-dictionary-according-to-both-keys-and-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...