user2578185
user2578185

Reputation: 437

Map list to dictionary according to value from other list

I have this list:

[0,0,3,3,0,1,1,1,3,3,0,2,0,2,0,0,2,2]

and this list:

[18,23,56,34,23,67,89,43,12,22,34,21,54,23,67,12,45,67]

(their lengths are the same)..I'd like to find a way to generate a dictionary from these lists by using as keys of the dict the values from the first list and as the values of each key the numbers of the second list corresponding to the position of the first list..

So the result would be:

dict = {'0': '18,23,23,34,54,67,12', '1':'67,89,43',.........} 

How can I implement this..any help is appreciated

Upvotes: 1

Views: 205

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122336

You can do:

>>> list1 = [0,0,3,3,0,1,1,1,3,3,0,2,0,2,0,0,2,2]
>>> list2 = [18,23,56,34,23,67,89,43,12,22,34,21,54,23,67,12,45,67]
>>> import collections
>>> result = collections.defaultdict(list)
>>> for i, j in zip(list1, list2):
...     result[i].append(j)
...
>>> result
defaultdict(<type 'list'>, {0: [18, 23, 23, 34, 54, 67, 12], 1: [67, 89, 43], 2: [21, 23, 45, 67], 3: [56, 34, 12, 22]})
>>> result[0]
[18, 23, 23, 34, 54, 67, 12]
>>> result[1]
[67, 89, 43]

To get the data structure as described in your question, you can do:

>>> for key, values in result.items():
...     result[str(key)] = ','.join(str(v) for v in values)

Upvotes: 5

Related Questions