[英]List of Lists to Dictionary of Lists
I am having a hard time converting a list of lists to a dictionary of lists due to some of the key values being the same, I am also getting an issue with the null value.由于某些键值相同,我很难将列表列表转换为列表字典,我也遇到了空值问题。 My List is:
我的清单是:
L = [['shark', ['one']], ['shark',['two']], ['fish', ['one']], ['fish', ['two']], ['fish',[]]]
My desired dictionary of lists would be structured like this:我想要的列表字典的结构如下:
Dic = {'shark': ['one','two'], 'fish':['one', 'two', '0']}
Is there any trick to be able to get the same key values to combine into a dictionary of lists like this?有什么技巧可以将相同的键值组合成这样的列表字典吗?
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
output:输出:
{'shark': ['one', 'two'], 'fish': ['one', 'two', '0']}
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']]})
if you need '0' instead of [] then add an if clause to the loop如果您需要 '0' 而不是 [] 然后在循环中添加一个 if 子句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.