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!
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With