列表字典列表清单

时间:2015-09-21 01:25:51

标签: python list dictionary

由于某些键值相同,我很难将列表列表转换为列表字典,我也遇到了null值的问题。我的名单是:

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

我想要的列表字典的结构如下:

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

是否有任何技巧可以将相同的键值组合成这样的列表字典?

2 个答案:

答案 0 :(得分: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']}

答案 1 :(得分: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子句