我是python的新手,我正在尝试使用元组作为键和嵌套列表作为多个值来创建字典。
列表嵌套在三元组中; [[[Isolation source],[host],[country]]...etc]
以下示例:
value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]....]
键的元组;
key_tuple = ('AB479448', 'AB479449', 'AB602436',...)
因此,我希望输出看起来像这样;
dict = {'AB479448': [NaN, sponge, Palau], 'AB479449': [skin, fish, Cuba], 'AB602436': [claw, crab, Japan: Aomori, Natsudomari peninsula]
我尝试了一些不同的解决方案但不是我可以开展工作......例如字典理解;
dict = { i: value_list for i in key_tuple }
上面给出了这个(使用不同的键但是将相同的值与每个键相关联);
{'AB479448': [[[NaN, sponge, Palau]]], 'AB479449': [[[NaN, sponge, Palau]]], 'AB602436': [[[NaN, sponge, Palau]]]...etc..}
非常感谢任何指示......谢谢!
答案 0 :(得分:7)
您可以使用itertools.chain.from_iterable
,itertools.izip
(或zip
)和词典理解:
>>> from itertools import chain, izip
>>> value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
>>> key_tuple = ('AB479448', 'AB479449', 'AB602436')
>>> {k: list(chain.from_iterable(v)) for k, v in izip(key_tuple, value_list)}
{'AB479449': ['skin', 'fish', 'Cuba'],
'AB479448': ['NaN', 'sponge', 'Palau'],
'AB602436': ['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']}
答案 1 :(得分:1)
value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
key_tuple = ('AB479448', 'AB479449', 'AB602436')
dict( (key,[[list(value)]]) for key,value in zip(key_tuple, zip(*(iter(t[0] for v in value_list for t in v),)*3)))
Out[16]: {'AB479448': [[['NaN', 'sponge', 'Palau']]], 'AB479449': [[['skin', 'fish', 'Cuba']]],'AB602436': [[['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']]]}
如果列表键中所需的元素数量发生变化,您可以用3
替换新的元素
长度值。
制作它真的很有趣。
答案 2 :(得分:1)
以下是使用itertools.chain.from_iterable
和字典理解的解决方案:
from itertools import chain
{keys[i]:list(chain.from_iterable(contents)) for i, contents in enumerate(my_list)}
这等于:
from itertools import chain
for i, contents in enumerate(my_list): #get [['skin'], ['fish'], ['Cuba']]
result[keys[i]] = list(chain.from_iterable(contents))
<强>演示强>:
>>> from itertools import chain
>>> my_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
>>> keys = ('AB479448', 'AB479449', 'AB602436')
>>> {keys[i]:list(chain.from_iterable(contents)) for i, contents in enumerate(my_list)}
{'AB479449': ['skin', 'fish', 'Cuba'], 'AB479448': ['NaN', 'sponge', 'Palau'], 'AB602436': ['claw', 'crab', 'Japan: Aomori, Natsudomari peninsula']}
>>>
希望这有帮助!