按其他列表或词典对词典进行排序

5 python sorting

我需要按确定您的订单的其他元素字典进行排序。

unsorted_dict = {'potato':'whatever1', 'tomato':'whatever2', 'sandwich':'whatever3'}
Run Code Online (Sandbox Code Playgroud)

这种排序可以列表或字典的形式进行,以较容易的一种为准。

ordination = ['sandwich', 'potato', 'tomato']
Run Code Online (Sandbox Code Playgroud)

排序后的字典:

sorted_dict = {'sandwich':'whatever3', 'potato':'whatever1', 'tomato':'whatever2'}
Run Code Online (Sandbox Code Playgroud)

imr*_*eal 9

你可以使用OrderedDict这样的:

from collections import OrderedDict

sorted_dict = OrderedDict([(el, unsorted_dict[el]) for el in ordination])
Run Code Online (Sandbox Code Playgroud)

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

它具有与 a 相同的接口,dict并且不引入任何外部依赖项。

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