同时根据键和值对字典进行排序

时间:2021-06-17 19:29:51

标签: python sorting dictionary

我有一个看起来像这样的字典:

{0: 2, 1: 4, 2: 2, 3: 2, 4: 5}

也就是说,键和值都是整数。

我需要以这种方式对这个字典进行排序:

  • 按值在前,升序;
  • 按键,如果值一致,则降序。

我所知道的是,python 的 sorted() 函数支持一个名为“key”的参数,但它似乎只允许一次拥有键或值。

我能做些什么来实现?

仅供参考,结果应该是:

{2: 2, 0: 2, 3: 2, 1: 4, 4: 5}

3 个答案:

答案 0 :(得分:2)

没有一种简单的方法可以说“这个值,升序,然后这个值,降序”。然而,如果你对一个整数列表中的每一个都取反,然后对它进行排序,那么这与反向排序是一样的。

这定义了一个元组的排序键:

  • 第一个值是每个字典项的值。
  • 第二个值是每个字典项的键,但被否定。
d = {0: 2, 2: 2, 3: 2, 1: 4, 4: 5}


def sort_key(item):
    key, value = item
    return value, -key


print(sorted(d.items(), key=sort_key))

输出:

[(3, 2), (2, 2), (0, 2), (1, 4), (4, 5)]

看到了吗?项目按值分组,如果出现平局,则按键按降序分组。

答案 1 :(得分:1)

字典无法真正排序,但从 3.6 开始,它们保留插入顺序,因此您可以从前一个字典的已排序元组项创建一个新字典。

要得到你想要的东西,你必须这样做两次——一次是键,然后是值。 这是有效的,因为 python 的 sorted 保证是“稳定的”——如果两个项目相同,那么它不会改变它们,所以如果两个值匹配,第二个值排序将保留初始键排序。

input_dictionary = {0: 2, 1: 4, 2: 2, 3: 2, 4: 5}
sorted_by_key = dict(sorted(input_dictionary.items(), key=lambda x: x[0], reverse=True))
sorted_by_both = dict(sorted(sorted_by_key.items(), key=lambda x: x[1]))
print(sorted_by_both)

Demo

答案 2 :(得分:1)

How do I sort a dictionary by value?

data = {0: 2, 1: 4, 2: 2, 3: 2, 4: 5}
sorted_data = dict(sorted(data.items(), key=lambda item:item[1]))
print(sorted_data)

输出

{0: 2, 2: 2, 3: 2, 1: 4, 4: 5}