Python 基于多个键值和比较规则排序dict对象

Python 基于多个键值和比较规则排序dict对象,python,dictionary,Python,Dictionary,我有一个dict对象数组,我应该根据多个规则对其进行排序 下面是示例dicts的外观: 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

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

下面是示例dicts的外观:

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\u list
按值列出对象(期望结果):

key1
key2
中,我可以为比较创建一个绝对数,但不幸的是,我不能这样做,因为
key3
仍然存在,我不能使用相同的逻辑


所以我的问题是:是否有可能定义我自己的排序规则?对于这样的任务,有Python函数吗?

如果我理解正确,您希望添加键1和键2,减去键3,并按此数字从高到低排序?如果是,请执行以下操作:

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

它的作用是将值映射到整数,然后从键3的值中减去键1和键2的值,因为它将它们从低到高排序。它将使您的原始词典保持所需的顺序。

那么,当您有{key1:2,key3:1}和{key1:1,key3:2}时,您会怎么做?您可以使用键函数定义自己的顺序,请参见
list_dicts = sorted(list_dicts, key=lambda x:int(x['key3'])-int(x['key2'])-int(x['key1']))