Reputation: 127
So I have a number of seperate lists:
[1,2,3]
[4,5,6]
[7,8,9]
Now I would like to convert these three separate lists into a dict such as this:
{1:4,7, 2:5,8, 3:6,9}
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?)...
now I understand such a thing could be achieved by what is known as the grouper recipe (itertools, etc)... if it were the case the lists were like this:
([1,2,3],[4,5,6],[7,8,9])
But it is not like that... I cant wrap my head around trying to do this with separate lists.
Upvotes: 0
Views: 81
Reputation: 10254
import collections
def change(*L):
res = collections.defaultdict(list)
T = list(zip(*L[1:]))
for i, key in enumerate(L[0]):
res[key] = T[i]
return res
L1 = [1, 2, 3, 10]
L2 = [4, 5, 6, 11]
L3 = [7, 8, 9, 12]
L4 = [13, 14, 15, 16]
print(change(L1, L2, L3, L4))
The output is: {1: (4, 7, 13), 2: (5, 8, 14), 3: (6, 9, 15), 10: (11, 12, 16)})
Please use this code, you can handle any number of list.
Upvotes: 0
Reputation: 239453
You can use zip and dictionary comprehension like this
l1, l2, l3 = [1,2,3], [4,5,6], [7,8,9]
data = [l1, l2, l3]
print {k:[v1, v2] for k, v1, v2 in zip(*data)}
Output
{1: [4, 7], 2: [5, 8], 3: [6, 9]}
Edit: If the lists are prepared in a loop, data
can be composed with list comprehension like this
data = [[j for j in range(i * 3, i * 3 + 3)] for i in range(3)]
Upvotes: 4
Reputation: 304137
The general form of @thefourtheye's answer - ie. works with more than 3 lists
print {i[0]:i[1:] for i in zip(*data)}
and a version that doesn't use a dict comprehension (unpacking works similar to the Python3 verison)
print dict(map(lambda k, *v: (k, v), *data))
Upvotes: 2
Reputation: 113915
Python3 has new and improved unpacking syntax:
>>> L1
[1, 2, 3]
>>> L2
[4, 5, 6]
>>> L3
[7, 8, 9]
>>> data = [L1,L2,L3]
>>> {k:v for k, *v in zip(*data)}
{1: [4, 7], 2: [5, 8], 3: [6, 9]}
However, this is not available in python2.x, so you'd have to go with @thefourtheye's answer on that front
Upvotes: 4