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

11

我需要通过另一个元素来确定顺序,对我的字典进行排序

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

这种排序可以作为列表或字典呈现,取决于哪种更容易。

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

排序后的字典:

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

你使用的是哪个版本的Python?为什么不使用有序字典呢? - MooingRawr
2
默认字典是未排序的。 - depperm
字典是无序的。你是想按排序后的方式打印出项目,还是按排序后的方式迭代键/值?正如@MooingRawr所说,collections.OrderedDict会记录添加键的时间,使您能够以相同的顺序遍历它们。 - Michael Speer
1
Python 3.7会保留你插入的顺序,因此可以“排序”字典...因此问题是哪个版本的Python。 - MooingRawr
Python 2.7。我找到的排序是按字母顺序或类似方式制作的,我需要自定义排序。 - user9451912
2个回答

10

您可以使用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也会保留插入顺序。

在Python 3.6+中,您可以使用常规字典。您可能希望添加两个选项。而且,您的列表推导式有拼写错误。 - pylang
1
@pylang 已编辑。您的评论有两个错别字。 ;) - imreal
@LucasdeLima 你的意思是过滤吗? - imreal
在列表推导式中添加一个 if - imreal
1
已经注意到了。承认你的观点。 - pylang
显示剩余2条评论

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'}

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


它能够工作,但我担心会弄乱我的代码,因为字典的值可以是任何东西,而元组我认为是不可能的。 - user9451912

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接