2014-02-14 29 views
7

我有一本字典如何排序依據列表上一本字典在python

a = {'ground': obj1, 'floor 1': obj2, 'basement': obj3} 

我有一個列表。

a_list = ['floor 1', 'ground', 'basement'] 

我想基於列表使用其鍵的字典排序。有可能這樣做嗎?

即:

sort(a).based_on(a_list) #this is wrong. But I want something like this. 
+1

字典*沒有順序*,所以你不能排序的字典。你想要一個排序的值列表嗎?或者是一個鍵值元組的排序列表? –

+0

@MartijnPieters任何事情我會不介意將字典轉換爲元組,然後對它們進行排序... – Wagh

回答

8

用簡單的方式,分選的(鍵,值)元組的列表:

sorted(a.items(), key=lambda pair: a_list.index(pair[0])) 

比較快的方式,首先創建一個索引圖:

index_map = {v: i for i, v in enumerate(a_list)} 
sorted(a.items(), key=lambda pair: index_map[pair[0]]) 

兩者都假設a_list包含全部鍵找到a

演示:

>>> a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'} 
>>> a_list = ('floor 1', 'ground', 'basement') 
>>> sorted(a.items(), key=lambda pair: a_list.index(pair[0])) 
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')] 
>>> index_map = {v: i for i, v in enumerate(a_list)} 
>>> sorted(a.items(), key=lambda pair: index_map[pair[0]]) 
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')] 
6

你可以只檢索值由列表中提供的按鍵順序,並作出新的清單出來的鍵值對的。

例子:

d = a  # dictionary containing key-value pairs that are to be ordered 
l = a_list # list of keys that represent the order for the dictionary 
# retrieve the values in order and build a list of ordered key-value pairs 
ordered_dict_items = [(k,d[k]) for k in l]