简体   繁体   English

从有序列表中的键排序字典值

[英]Sort of dictionary values from keys in an ordered list

Say I have the following dictionary: 说我有以下字典:

FruitValues={'Banana':3, 'Orange':4, 'Apple':1}

And I have a list of the keys of this dictionary in a order that I want to preserve: 而且我要保留的顺序列出了该词典的键:

SortOrder=['Orange', 'Apple', 'Banana']

What is the most efficient way of getting a list of the values from the dictionary in the order of the list? 按列表顺序从字典中获取值列表的最有效方法是什么?

Right now my approach is the following: 现在,我的方法如下:

OrderedValues=[]
for Fruit in SortOrder:
    OrderedValues.append(FruitValues[Fruit])
print OrderedValues

[4, 1, 3]

Is there a better / cleaner way of doing this? 有更好/更清洁的方法吗? Maybe using a dictionary comprehension? 也许使用字典理解?

Use list comprehension: 使用清单理解:

>>> [FruitValues[i] for i in SortOrder]
[4, 1, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM