2016-05-30 88 views
-1

我有一个字典对象数组,我必须根据多个规则进行排序。基于多个键值和比较规则排序字典对象

这是样品类型的字典的样子:

dict1 = {'key1': '85', 'key2': '163', 'key3': '3'} 
dict2 = {'key1': '3', 'key2': '23', 'key3': '1'} 
dict3 = {'key1': '88', 'key2': '153', 'key3': '6'} 

而且这些规则应遵循的顺序:

key1 - the higher value is the better 
key2 - the higher value is the better 
key3 - the lower value is the better 

订货我的名单应该是这样的所以以后:

dict_list = [dict1, dict3, dict2] 

#dict1 is the first obj, because it has the biggest key1 + key2 value and the 2. lowest key3 value 

dict_list物件按价值(预期结果):

# value name - high values (key1 + key2) - low values (key3) 
1. dict1     248      3 
2. dict3     241      6 
3. dict2     26      1 

key1key2我可以创建用于比较的绝对数量,但不幸的是,我不能这样做,因为key3将仍然存在,我不能使用相同的逻辑吧。

所以我的问题:是否有可能为排序定义我自己的规则?有没有这样的任务的Python功能?

+0

那么当你有{key1:2,key3:1}和{key1:1,key3:2}时你会怎么做? –

+0

您可以使用键功能定义您自己的订购请参阅https://wiki.python.org/moin/HowTo/Sorting – pvg

回答

2

如果我理解正确,您想要添加键1和键2并减去键3并将它们从高到低排序在这个数字上?如果是这样,这样做:

list_dicts = sorted(list_dicts, key=lambda x:int(x['key3'])-int(x['key2'])-int(x['key1'])) 

这样做是你的值映射到整数,从键3的值中减去的键1和键2的值,因为他们听命于低到高。它会保留你原来的字典,只是按照想要的顺序。