python - Sort of dictionary values from keys in an ordered list -


say have following dictionary:

fruitvalues={'banana':3, 'orange':4, 'apple':1} 

and have list of keys of dictionary in order want preserve:

sortorder=['orange', 'apple', 'banana'] 

what efficient way of getting list of values dictionary in order of list?

right approach following:

orderedvalues=[] fruit in sortorder:     orderedvalues.append(fruitvalues[fruit]) print orderedvalues  [4, 1, 3] 

is there better / cleaner way of doing this? maybe using dictionary comprehension?

use list comprehension:

>>> [fruitvalues[i] in sortorder] [4, 1, 3] 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -