在Python中,我有一个字典,并希望它根据与存储在列表中的字典中的键匹配的值的顺序进行排序。假设以下内容:
value_dict = {"Alpha": "The Alpha", "Beta": "The Beta", "Gamma": "The Gamma"}
key_order = ["Beta", "Gamma", "Alpha"]
因此,在这种情况下,我希望对字典进行排序,这样键“ Beta”首先出现,然后是“ Gamma”,然后是“ Alpha”。
有什么好主意我会怎么做?
答案 0 :(得分:2)
value_dict = {"Alpha": "The Alpha", "Beta": "The Beta", "Gamma": "The Gamma"}
key_order = ["Beta", "Gamma", "Alpha"]
# OrderedDict will keep the sequence intact
from collections import OrderedDict
OrderedDict(zip(key_order, [value_dict[i] for i in key_order]))
# OrderedDict([('Beta', 'The Beta'),
# ('Gamma', 'The Gamma'),
# ('Alpha', 'The Alpha')])
答案 1 :(得分:1)
尝试一下(使用带键功能的sorted()):sorted(value_dict.items(), key=lambda pair: key_order.index(pair[0]))