我需要按照另一个确定您的顺序的元素对我的字典进行排序。
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/