Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting many lists into single dict

I have a function which loops, and prints many, arbitrary number of separate lists.

example:

EDIT: This is the output I get when I run my function.

['Hello', 'Mello', 'Jello']
['Sun', 'Fun', 'Run']
['Here', 'There', 'Everywhere'}

Now I would like to convert these arbitrary separate lists into a dict such as this:

{'Hello':['Sun','Here'], 'Mello':['Fun', 'There'], 'Jello':['Run', 'Everywhere']}

Where each of the elements in the first list become the 'keys' and the all the elements under become the 'values' (or is it the otherway around?)...

What I tried was:

{k:v for k, *v in zip(*data)}

But when I do this, I get an output something like this:

{'1': ('T', 'P', '2'), '7': ('a', '.', '6'), '9': ('t', 'r', '8')}
{'0': ('h', 'L', '1'), '2': ('T', 'N', '1')}
{'0': ('o', 'V', '0'), '2': ('T', 'B', '1')}
like image 632
user3029969 Avatar asked Jan 18 '26 13:01

user3029969


1 Answers

>>> L1 = ['Hello', 'Mello', 'Jello']
>>> L2 = ['Sun', 'Fun', 'Run']
>>> L3 = ['Here', 'There', 'Everywhere']
>>> {k:v for k, *v in zip(L1, L2, L3)}
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}

It's not clear what you had in data, but this works fine

>>> data = [L1, L2, L3]
>>> {k:v for k, *v in zip(*data)}
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}

Other options are

>>> dict(map(lambda k, *v:(k, v), *data))
{'Hello': ('Sun', 'Here'), 'Mello': ('Fun', 'There'), 'Jello': ('Run', 'Everywhere')}



>>> dict(map(lambda k, *v:(k, list(v)), *data))
{'Hello': ['Sun', 'Here'], 'Mello': ['Fun', 'There'], 'Jello': ['Run', 'Everywhere']}
like image 177
John La Rooy Avatar answered Jan 21 '26 04:01

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!