python - 按另一个列表或字典对字典进行排序

标签 python sorting

我需要按照另一个确定您的顺序的元素对我的字典进行排序

unsorted_dict = {'potato':'whatever1', 'tomato':'whatever2', 'sandwich':'whatever3'}

这种排序可以是列表或字典,以更容易的为准。

ordination = ['sandwich', 'potato', 'tomato']

排序后的字典:

sorted_dict = {'sandwich':'whatever3', 'potato':'whatever1', 'tomato':'whatever2'}

最佳答案

您可以像这样使用 OrderedDict:

from collections import OrderedDict

sorted_dict = OrderedDict([(el, unsorted_dict[el]) for el in ordination])

它的作用是创建一个元组(对)列表,使用ordination作为第一个元素,使用unsorted_dict中的值作为第二个元素,然后使用OrderedDict 使用此列表创建按插入排序的字典。

它具有与dict相同的接口(interface),并且不引入外部依赖项。

编辑:在 python 3.6+ 中,普通的 dict 也将保留插入顺序。

关于python - 按另一个列表或字典对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49243734/

相关文章:

python - 如何用plotly在卫星 map 上绘制箭头

python - 我无法使用cv2.imwrite()方法成像

python - Windows 的 Python 3.x 信号库是否不完整?

java - CompareTo 方法如何与 array.sort 一起使用来对数组进行排序?

java - 如何在单个对象中创建多个比较器

python - __init__() 需要 1 个位置参数,但 2 个给出了类型错误

python - 等待 asyncio.Future 引发 concurrent.futures._base.CancelledError 而不是等待设置值/异常

sorting - 更改下拉列表中关键字的默认顺序

sorting - Lisp 排序功能键

r - 将列中的唯一值更改为两个特定值之一