简体   繁体   English

通过值对python中的字典进行排序,但保持相等值的键顺序

[英]Sort a dictionary in python by values but maintaining the key order for equal values

Lets say there is a dictionary 可以说有一本字典

d = {"P1":77,"P2":89,"P3":77}

I want to print the results in following form 我想以下面的形式打印结果

P2: 89 P2:89

P1: 77 P1:77

P3: 77 P3:77

ie sorting by dictionary values and for equal values first one comes first(ie P1 comes before P3) 即按字典值排序,对于相等的值,首先是第一个(即P1在P3之前)

I did the following 我做了以下

import collections
od = collections.OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))

od gives od给出

OrderedDict([('P2', 89), ('P3', 77), ('P1', 77)])

How can I get P1 before P3 ? 如何在P3之前获得P1?

Do this: 做这个:

od = collections.OrderedDict(sorted(d.items(), key = lambda x:(-x[1],x[0])))

As @Padraic said, "You cannot sort from highest to lowest and lowest to highest." 正如@Padraic所说,“你不能从最高到最低,从最低到最高。” Therefore, you have to trick the sorted function by making it see the highest numbers as the lowest ones. 因此,您必须通过使排序函数看到最高数字作为最低数字来欺骗它。 It is sub-sorted by the natural order of the keys. 它按键的自然顺序进行子排序。

Python's sort is a stable sort, meaning items stay in their original order if they compare equal. Python的sort是一种稳定的排序,意味着如果项目比较相等,则项目保持原始顺序。 If you start with an OrderedDict and just sort on the value only, they keys will stay in their original order. 如果您从OrderedDict开始并仅对值进行排序,则它们将保持原始顺序。 In your case, however, sort them with a key that that sorts highest to lowest directly, instead of reversing the sort, to keep them in the same key order. 但是,在您的情况下,使用直接排序从最高到最低的键排序它们,而不是反转排序,以使它们保持相同的键顺序。

Example

from collections import OrderedDict
d = OrderedDict([('P1',77),('P2',89),('P3',77)])
print sorted(d.items(),key=lambda x:-x[1])
d = OrderedDict([('P3',77),('P2',89),('P1',77)])
print sorted(d.items(),key=lambda x:-x[1])

Output 产量

[('P2', 89), ('P1', 77), ('P3', 77)]
[('P2', 89), ('P3', 77), ('P1', 77)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM