Home > OS >  Regroup elements of a list with the help of one other list
Regroup elements of a list with the help of one other list

Time:06-29

I solved this problem, but my solution is slow and I'm sure it's not optimal. Here is the problem:

I have two lists. The first list contains dictionaries with id and some description (ids are unique; you can't have 2 dictionaries with the same id).

The second list contains lists which contain the ids of the dictionary who are linked (ex: if I have [78,22] it means that dictionary with id 78 and dictionary with id 22 are linked).

I want a list which contain lists which contain the dictionaries who are linked.

To be more clear, here is an example:

l1 = [
    {id:7, des:"..."},
    {id:2, des:"..."},
    {id:70, des:"..."},
    {id:300, des:"..."},
    {id:259, des:"..."},
    {id:57, des:"..."}
    ]
l2 = [[259,2], [7], [300,57,70]]

and I want

l3 = [
    [{id:2, des:"..."}, {id:259, des:"..."}],
    [{id:7, des:"..."}],
    [{id:300, des:"..."}, {id:70, des:"..."}, {id:57, des:"..."}]
    ]

The order is not important for me.

CodePudding user response:

Since the IDs are unique, you can make a lookup dict based on them, then just use a list comprehension over l2.

lookup = {d['id']: d for d in l1}
result = [[lookup[e] for e in sublist] for sublist in l2]

Result:

[[{'id': 259, 'des': '...'}, {'id': 2, 'des': '...'}],
 [{'id': 7, 'des': '...'}],
 [{'id': 300, 'des': '...'}, {'id': 57, 'des': '...'}, {'id': 70, 'des': '...'}]]
  • Related