gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:15:18 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com