Search code examples
pythonlistdefaultdict

How to extend one sublist by another sublist if they share a common id at the same index in both sublists?


What's the most efficient way of extending one sublist with another sublist if they share a common value at a particular index? I'd like to merge two sublists together if a value at index 0 of List1 is equal to the value of index 0 of List2.

List1 = [['aaa','b','c'],['ddd','e','f']]
List2 = [['aaa','1','2'],['ddd','3','4']]

Desired Output:

[['aaa','b','c','aaa','1','2'],['ddd','e','f','ddd','3','4']]

My hack:

from collections import defaultdict

Keys2 = map(lambda x: x[0], List2) #returns ['aaa','ddd']
List2_of_Tuples = zip(Keys,List2) #returns [('aaa',['aaa','1','2']),('ddd',['ddd','3','4'])]

Keys1 = map(lambda x: x[0], List1) 
List1_of_Tuples = zip(Keys,List1)

Merged_List_of_Tuples = List1_of_Tuples + List2_of_Tuples
d = defaultdict(list)
for k,v in Merged_List_of_Tuples:
    d[k].append(v)

Desired_Result = map(lambda x: [item for sublist in x[1] for item in sublist],d.items())

This returns:

[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]

I'm doing this to more than two large lists. Is there a shorter more efficient way of doing this?


Solution

  • list1,list2 = [['aaa','b','c'],['ddd','e','f']],[['aaa','1','2'],['ddd','3','4']]
    
    from itertools import chain, groupby
    from operator import itemgetter
    get_first, result = itemgetter(0), []
    for key, grp in groupby(sorted(chain(list1, list2), key = get_first), get_first):
        result.append([item for items in grp for item in items])
    print result
    

    Output

    [['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]