2015-09-21 99 views
-2

由於一些鍵值相同,我很難將列表列表轉換爲列表字典,我也遇到了空值問題。我的名單是:列表字典列表

L = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]] 

我的列表中所需的字典將結構是這樣的:

Dic = {'shark': ['one','two'], 'fish':['one', 'two', '0']} 

有什麼絕招能夠得到相同的密鑰值結合成列表的像一本字典這個?

+1

看一看'collections.defaultdict'。 – Akavall

回答

2
L = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]] 

p = {} 

for k, v in L: 
    d = p.setdefault(k, []) 
    if not v:v = ['0'] 
    d.extend(v) 

print p 

輸出:

{'shark': ['one', 'two'], 'fish': ['one', 'two', '0']} 
2
from collections import defaultdict 
dct = defaultdict(list) 
l = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]] 
for x in l: 
    dct[x[0]].append(x[1]) 
dct 
>>> defaultdict(list, 
     {'fish': [['one'], ['two'], []], 'shark': [['one'], ['two']]}) 

,如果你需要 '0',而不是if語句[],然後添加到循環