2013-02-02 15 views
0

我有一個基本列表排序使用的基本列表

li = ['fca', 'fc_add', 'fca_2', 'fcadd_2', 'Red_Exis', 'G_Exis', 'P_Exis', 'fam_1'] 

,並希望使用列表中的項目的索引位置排序如下字典

其中列表項的索引位置的字典項是鍵。

dic = {'G_Exis': 'abc', 'fca': '210Y', 'Red_Exis': 107, 'fc_add': '999 Des ST.'} 

我需要最終排序的字典如下所示:

fin_dic = {'fca': '210Y', 'fc_add': '999 Des ST.', 'Red_Exis': 107, 'G_Exis': 'abc'} 

多謝提前。

回答

2

快譯通的不守秩序,使用collections.OrderedDict

from collections import OrderedDict 
od = OrderedDict() 

for item in li: 
    if item in dic: 
     od[item] = dic[item] 
print od 

OrderedDict([('fca', '210Y'), ('fc_add', '999 Des ST.'), ('Red_Exis', 107), 
      ('G_Exis', 'abc')]) 

或作爲oneliner:

OrderedDict(sorted(dic.items(), key=lambda t: li.index(t[0])))