Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Making a dict from tuple keys with multiple values from a nested list

I am new to python and I am trying to make a dictionary using tuples as keys and a nested list as multiple values.

The list is nested in triplets; [[[Isolation source],[host],[country]]...etc]

example below:

value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]....]

And the tuple of keys;

key_tuple = ('AB479448', 'AB479449', 'AB602436',...)

Hence, I would like the output to look like this;

dict = {'AB479448': [NaN, sponge, Palau], 'AB479449': [skin, fish, Cuba], 'AB602436': [claw, crab, Japan: Aomori, Natsudomari peninsula]

I have tried a few different solution but non that I could make work... e.g. dictionary comprehension;

dict = { i: value_list for i in key_tuple }

The above gives me this (uses the different keys but associates the same value to each of them);

{'AB479448': [[[NaN, sponge, Palau]]], 'AB479449': [[[NaN, sponge, Palau]]], 'AB602436': [[[NaN, sponge, Palau]]]...etc..}

Would appreciate any pointers... thanks!

like image 762
jO. Avatar asked Nov 24 '25 03:11

jO.


1 Answers

You can use itertools.chain.from_iterable, itertools.izip (or zip) and a dict comprehension:

>>> 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']}
like image 174
Ashwini Chaudhary Avatar answered Nov 26 '25 15:11

Ashwini Chaudhary