Lauren
Lauren

Reputation: 61

Map two lists (one of which is a list of lists) into a dictionary

I have 2 lists:

List_1: [a,a,a,b,b,c,c,c,a,a]

and a corresponding list List_2: [{1,2,3},{5,6,9},{10},{11},{27,18,29},{1,2,3},{7,10},{34},{83},{60}] which is a list of sets for each of the elements in the List_1.

I need a dictionary keyed by the unique elements in list_1 and valued by their corresponding (concatenated) lists from list_2. So for example, the output I'd be looking for here would be:

Dict = {a:[1,2,3,5,6,9,10,83,60], b:[11,27,18,29], c:[1,2,3,7,10,34]}

My first instinct was dict(zip(list_1,list_2)) which obviously hasn't worked...

Any help appreciated :)

Upvotes: 2

Views: 86

Answers (3)

abhiarora
abhiarora

Reputation: 10430

Try this:

li_1 = ["a","a","a","b","b","c","c","c","a","a"]
li_2 = [{1,2,3},{5,6,9},{10},{11},{27,18,29},{1,2,3},{7,10},{34},{83},{60}]

di = { }
for ndx,i in enumerate(li_1):
    if i in di:
        di[i].extend(list(li_2[ndx]))
    else:
        di[i] = list(li_2[ndx])

print(di)

Outputs:

{'a': [1, 2, 3, 9, 5, 6, 10, 83, 60], 'b': [11, 18, 27, 29], 'c': [1, 2, 3, 10, 7, 34]}

To reduce the number of lines, you can use defaultdict from python collection module. Using this we can avoid if clause in the for loop.

from collections import defaultdict

li_1 = ["a","a","a","b","b","c","c","c","a","a"]
li_2 = [{1,2,3},{5,6,9},{10},{11},{27,18,29},{1,2,3},{7,10},{34},{83},{60}]

di = defaultdict(list)
for ndx,i in enumerate(li_1):
    di[i].extend(li_2[ndx])

print(dict(di))

My first instinct was dict(zip(list_1,list_2)) which obviously hasn't worked

dict(zip(list_1,list_2)) discards all but the last set associated with a key. See the below code:

di = defaultdict(list)
for i,j in zip(li_1, li_2):
    di[i].extend(j)

print(dict(di))

Upvotes: 0

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Use defaultdict from collections

>>> from collections import defaultdict
>>> my_dict = defaultdict(set)
>>> for k, v in zip(a, b):
...     my_dict[k] = my_dict[k].union(v)
... 
>>> dict(my_dict)
{'a': {1, 2, 3, 5, 6, 9, 10, 83, 60}, 'b': {27, 18, 11, 29}, 'c': {1, 2, 3, 34, 7, 10}}

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

Use a defaultdict:

from collections import defaultdict

list_1 = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'a', 'a']
list_2 = [{1, 2, 3}, {5, 6, 9}, {10}, {11}, {27, 18, 29}, {1, 2, 3}, {7, 10}, {34}, {83}, {60}]

result = defaultdict(list)
for e1, e2 in zip(list_1, list_2):
    result[e1].extend(e2)

print(result)

Output

defaultdict(<class 'list'>, {'a': [1, 2, 3, 9, 5, 6, 10, 83, 60], 'b': [11, 18, 27, 29], 'c': [1, 2, 3, 10, 7, 34]})

If you really need a dictionary, just do dict(result).

Upvotes: 1

Related Questions