首页 > 解决方案 > 如何在字典上应用排序算法?

问题描述

我有一本字典d

d = {3: 'a', 5: 'g', 1: 't', 4: 'y'}

我想对其进行排序,结果是:

d = {1: 't', 3: 'a', 4: 'y', 5: 'g'}

为了得到这个结果,我需要在列表上应用一个排序算法,比如插入排序或选择排序。如何实施?

标签: pythondictionaryinsertion-sort

解决方案


你想通过键对你的 dict 进行排序。如果我理解你,你想用你选择的排序算法(不是内置算法)对它们进行排序。

所以你应该:

  • 实现你的排序算法
  • 将其应用于 dict 键
  • 创建按键排序的新字典

伪代码:

d = {3: 'a', 5: 'g', 1: 't', 4: 'y'}

# Get the keys as list
d_keys = list(d.keys()) # [3, 5, 1, 4]

# Here, you implement your sorting algorithm on 'd_keys'
# ...
# At the end, you get 'sorted_keys' ('d_keys' sorted): sorted_keys == [1, 3, 4, 5]

# Here you create the new dictionary: (via dictionary comprehension):
sorted_dict = {k:d[k] for k in sorted_keys}

print(sorted_dict)

输出:

d = {1: 't', 3: 'a', 4: 'y', 5: 'g'}

您将在此处找到 Python 中的插入排序算法实现:Python 插入排序如何工作?

在这里选择排序:Selection Sort Python

但是,如果您要求的是“我可以将自己的算法传递给内置sorted方法”之类的东西,那么答案是否定的。但是,sorted允许您选择如何比较元素。您将在此处找到有关此内容的更多信息:https ://docs.python.org/3/howto/sorting.html并使用自定义比较函数对列表列表进行排序以及如何在 Python 3 中使用自定义比较函数?.


推荐阅读