0

I have 2 lists from which I would like to create a dict.

my list1 is:

[1,2,2,3]

my list2 is:

[['A','B'],['J','K'],[L'','M'],['W','X']]

I would like to make a

dict(zip(list1,list2))

However given that list1 has a repeated key I am loosing one key 2 with its values.

So I would like to join the sublists of list2 based on the repeated values in list 1 .

list1 and list2 are indexed in same order.

The desired output would be :

[['A','B'],['J','K','L','M'],['W','X']]

So I can remove dups of list1 and make the

dict(zip(list1_without_dups,list2_merged_sublists))    

Sorry I do not include my try but i have been seeking for similar issues unsuccesfully and not sure how to face it.

2 Answers 2

4

Use collections.defaultdict:

from collections import defaultdict

lst1 = [1,2,2,3]
lst2 = [['A','B'],['J','K'],['L','M'],['W','X']]

d = defaultdict(list)

for x, y in zip(lst1, lst2):
    d[x].extend(y)

print(d)

which outputs:

defaultdict(<class 'list'>, {1: ['A', 'B'], 2: ['J', 'K', 'L', 'M'], 3: ['W', 'X']})

You can now extract values to get the desired list.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use itertools.groupby:

from itertools import groupby as g, chain as c
d =  [1,2,2,3]
new_d = [['A','B'],['J','K'],['L','M'],['W','X']]
r = [list(c(*[j for _, j in b])) for _, b in g(list(zip(d, new_d)), key=lambda x:x[0])]

Output:

[['A', 'B'], ['J', 'K', 'L', 'M'], ['W', 'X']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.