2013-03-13 113 views
4

如何將列表列表轉換爲詞典列表?列表到詞典列表

更多specifiicaly:我如何從這個去:

[['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']] 

這樣:

[{'a1': None, 'b1': None, 'c1': None, 'd1': None, 'e1': None, 'f1': None, 'g1': None, 'h1': None, 'i1': None}, #etc 
+0

固定標題爲您服務。 – 2013-03-13 08:24:20

回答

22
In [20]: l = [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']] 

In [21]: map(dict.fromkeys, l) 
Out[21]: 
[{'a1': None, 
    'b1': None, 
    'c1': None, 
    'd1': None, 
    'e1': None, 
    'f1': None, 
    'g1': None, 
    'h1': None, 
    'i1': None}, 
{'a2': None, 
    'b2': None, 
    'c2': None, 
    'd2': None, 
    ... 

這將iterables的可迭代的,不只是列出的清單工作(當然,提供的二級元素是hashable)。

在Python 2中,上面的代碼返回一個列表。

在Python 3中,它返回一個迭代。如果你需要一個列表,你可以使用list(map(dict.fromkeys, l))

+6

絕對優雅。 – msvalkon 2013-03-13 08:22:51

+0

原諒我,因爲我可能在做一些非常基本的錯誤(因爲這個答案有19個快樂的讀者),但是這段代碼似乎產生了錯誤:'<0x02F3E210>的地圖對象'。我究竟做錯了什麼? – LazySloth13 2013-03-13 16:31:07

+0

@Lewis:聽起來你正在使用Python 3.在這種情況下,使用'list(map(dict.fromkeys,l))'。我會更新答案。 – NPE 2013-03-13 16:35:29

3

試試這個:

l = [['a1', 'b1', 'c1', 'd1', 'e1', 'f1', 'g1', 'h1', 'i1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2', 'g2', 'h2', 'i2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3', 'g3', 'h3', 'i3'], ['a4', 'b4', 'c4', 'd4', 'e4', 'f4', 'g4', 'h4', 'i4'], ['a5', 'b5', 'c5', 'd5', 'e5', 'f5', 'g5', 'h5', 'i5'], ['a6', 'b6', 'c6', 'd6', 'e6', 'f6', 'g6', 'h6', 'i6'], ['a7', 'b7', 'c7', 'd7', 'e7', 'f7', 'g7', 'h7', 'i7'], ['a8', 'b8', 'c8', 'd8', 'e8', 'f8', 'g8', 'h8', 'i8'], ['a9', 'b9', 'c9', 'd9', 'e9', 'f9', 'g9', 'h9', 'i9']] 
res = [] 
for line in l: 
    res.append(dict((k, None) for k in line)) 

OR:

res = [dict((k, None) for k in line) for line in l]