2017-04-25 113 views
0

儘管在stackoverflow上有很多答案,但我仍然在寫這個問題,因爲解決方案對我的問題無效。我有2個列表,List1List2。當我dict(zip(List1,List2))字典內的元素順序受到干擾。Python:列表到詞典

print s_key 
print value 
sorted_dict = {k: v for k,v in zip(s_key,value)} 
another_test = dict(zip(s_key,value)) 
print sorted_dict 
print another_test 
print zip(s_key,value)) 

終端:

[2, 1, 3] 
[31, 12, 5] 
{1: 12, 2: 31, 3: 5} 
{1: 12, 2: 31, 3: 5} 
[(2, 31), (1, 12), (3, 5)] 

我的印象是,[(2, 31), (1, 12), (3, 5)]將被轉換爲一個dict

任何有助於明白的地方或什麼,我做錯了會幫助!謝謝!

+8

字典無序。如果您需要特定訂單,請使用['OrderedDict'](https://docs.python.org/2/library/collections.html#collections.OrderedDict)。 – khelwood

+0

你不能像這樣排序字典。我會推薦閱讀哈希表 – user3684792

回答

5
a=[2, 1, 3] 
b=[31, 12, 5] 
from collections import OrderedDict 
print(OrderedDict(zip(a,b))) 
0

您不能對一個字典,你的情況,如果你想顯示你的字典的排序鍵/值,您可以將其轉換爲一個元組列表,你已經和你所需要的任何元素排序。在它下面的代碼創建的第一個元素的元組和排序的元組的列表:

l1,l2=[2, 1, 3],[31, 12, 5] 
print ([(one,two) for (one,two) in 
     sorted(zip(l1,l2),key=lambda pair: pair[0])]) 

打印:

[(1, 12), (2, 31), (3, 5)] 

大喊答題節目環節以Sorting list based on values from another list?的幫助

要麼或創建列表中的字典鍵和排序列表,然後遍歷列表並調用每個鍵

或使用有序的字典作爲別人指出