2014-12-27 56 views
-4

下面的元組的列表:元組到字典中

x= [('a',1),('b', 2)] 

我想將其轉換爲:

x_1 = {'a' : 1, 'b': 2} 

如果我使用字典(X),該字典變得無序,我想它以完全相同的順序。 真的需要爲我的課程作業,請大家幫忙快速

回答

0

使用collections.OrderedDict()如果順序必須保存:

>>> from collections import OrderedDict 
>>> x= [('a',1),('b', 2)] 
>>> x_1 = OrderedDict(x) 
>>> for key in x_1: 
...  print(key) 
... 
a 
b 
+0

這工作完美,直到我打印出的鍵和值,程序說ValueError:太多的值解壓(預期2) 我用這個,因爲我希望他們在同一行: 的關鍵在x_1: print(key,values) – 2014-12-27 16:20:09

+0

@PratyushKhurana,'x_1.items()'同時返回'key'和'value',簡單的迭代在'x_1'上只返回'key'。因此,使用'for key,x_1:print(key,values)'中的值'來代替。 – 2014-12-27 16:37:02

+0

@PratyushKhurana:聽起來像你想迭代'x_1.items()'而不是那麼。 – 2014-12-27 16:58:16

0

你需要collections.ordereddict

>>> from collections import OrderedDict 
>>> x= [('a',1),('b', 2)] 
>>> x = OrderedDict(x) 
>>> x 
OrderedDict([('a', 1), ('b', 2)]) # Order is preserved 

這看起來並不像Python字典,但它實際上可以從下面的例子中看出:

>>> x['a'] 
1 
>>> x['b'] 
2 
>>> for key,val in x.items(): 
... print(key,val) 
... 
a 1 
b 2 
0

根據定義,字典在Python(或關聯數組)無序數據結構,其存儲鍵值數據,並允許用戶快速的方式由下式給出,添加到提取一對新的鍵值或刪除現有的一對。這個數據結構必須是無序的,以使所有必要的算法能夠快速工作。

有關字典的更多信息,請參閱wikipedia

如果您確實需要使用密鑰順序,我建議您分別創建字典和列表或密鑰。它會佔用更多的內存,但通常會更快。

x = [('a', 1), ('b', 2)] 

dct = dict(x) # dictionary 
kys = zip(*x)[0] # tuple of keys 

祝你好運!