简体   繁体   中英

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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