儘管在stackoverflow
上有很多答案,但我仍然在寫這個問題,因爲解決方案對我的問題無效。我有2個列表,List1
和List2
。當我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
任何有助於明白的地方或什麼,我做錯了會幫助!謝謝!
字典無序。如果您需要特定訂單,請使用['OrderedDict'](https://docs.python.org/2/library/collections.html#collections.OrderedDict)。 – khelwood
你不能像這樣排序字典。我會推薦閱讀哈希表 – user3684792