按另一个列表或字典对字典排序

时间:2018-03-12 20:16:03

标签: python sorting

我需要排序我的字典由另一个决定您订单的元素。

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

这种排序可以作为列表或字典,以较容易的方式出现。

ordination = ['sandwich', 'potato', 'tomato']
排序后的

词典:

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

2 个答案:

答案 0 :(得分:1)

您可以像这样使用OrderedDict

from collections import OrderedDict

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

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

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

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

答案 1 :(得分:0)

我认为这是最简单的方法:

sorted_dict = dict()
sorted_list = list((i, unsorted_dict.get(i)) for i in ordination)
for i in sorted_list:
    sorted_dict.setdefault(i[0], i[1])

结果是:

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

这和第二个答案一样,首先创建一个排序对的元组,但不依赖于任何外部库。

相关问题