[英]How to sort a dictionary based on a list in python
我有一本字典
a = {'ground': obj1, 'floor 1': obj2, 'basement': obj3}
我有一個清單。
a_list = ['floor 1', 'ground', 'basement']
我想使用基於列表的鍵對字典 a 進行排序。 有可能這樣做嗎?
IE:
sort(a).based_on(a_list) #this is wrong. But I want something like this.
輸出不必是另一個字典,我不介意將字典轉換為元組然后對它們進行排序。
天真的方式,使用sorted()
函數和自定義排序鍵(為dict.items())
生成的每個(key, value)
對調用(key, value)
對(鍵,值)元組列表進行sorted()
dict.items())
:
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]])
這更快,因為index_map
的字典查找需要O(1)常量時間,而a_list.index()
調用每次都必須掃描列表,因此需要O(N)線性時間。 由於針對字典中的每個鍵值對調用該掃描,因此天真排序選項采用O(N ^ 2)二次時間,而使用映射使得排序保持有效(O(N log N),線性時間)。
兩者都假設a_list
包含在a
找到的所有鍵。 但是,如果是這種情況,那么您也可以反轉查找並按順序檢索鍵 :
[(key, a[key]) for key in a_list if key in a]
這需要O(N)線性時間,並允許a_list
中的額外鍵不存在於a
。
明確:O(N)> O(N log N)> O(N ^ 2),請參閱此備忘單以供參考 。
演示:
>>> 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')]
>>> [(key, a[key]) for key in a_list if key in a]
[('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')]
您可以按列表提供的鍵的順序檢索值,並從鍵值對中創建一個新列表。
例:
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]
這對我有用:
a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'}
a_list = ['floor 1', 'ground', 'basement']
ordered_dict = {}
for item in a_list:
ordered_dict[item] = a[item]
print(ordered_dict)
{'floor 1': 'obj2', 'ground': 'obj1', 'basement': 'obj3'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.