根据多个键值和比较规则对dict对象进行排序

时间:2016-05-30 17:33:21

标签: python dictionary

我有一个dict对象数组,我应该根据多个规则进行排序。

这就是样本序列的样子:

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函数?

1 个答案:

答案 0 :(得分:2)

如果我理解正确你想要添加键1和键2并减去键3并在这个数字上从高到低排序?如果是这样,请执行以下操作:

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

这样做是将值映射到整数,并从键3的值中减去键1和键2的值,因为它将它们从低到高排序。它将保留您原来的词典,只需按照所需的顺序。