How to group two dictionary items into one list entry from another?

Question:

l1 = [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1},
      {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2},
      {'_id': 2, 'type': 'int', 'name': 'one', 'des': 1},
      {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]

l2 = [{'g_id': 0, 'type': 'group1', 'name': 'first',},
      {'g_id': 1, 'type': 'group2', 'name': 'second'},]

How do I group items like this? Referring to the previous two pieces of data, extract two items from list1 and group them with list2?

group_result = [{'g_id': 0, 'type': 'group1', 'name': 'first',
                'group':[{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1},
                         {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}]},
                {'g_id': 1, 'type': 'group1', 'name': 'first',
                'group':[{'_id': 2, 'type': 'int', 'name': 'one', 'des': 1},
                         {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]}]
Asked By: I'm not a cat

||

Answers:

if you are using Python >= 3.9, you can use dict concatenation (assuming that len(l1) is two times len(l2)):

[grp | {'group': grp_ids}
 for grp, grp_ids in zip(l2, [l1[i*2:(i+1)*2] for i in range(len(l2))])]

The result is:

[{'g_id': 0, 'type': 'group1', 'name': 'first', 'group': [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}]}, {'g_id': 1, 'type': 'group2', 'name': 'second', 'group': [{'_id': 2, 'type': 'int', 'name': 'one', 'des': 1}, {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]}]
Answered By: PieCot

Normal list comprehension will be suffice for this

group_result=[ {**l2[i], **{"group": l1[2*i: (2*i)+2]}} for i in range(0, len(l2))]

OUTPUT

[{'g_id': 0,
  'type': 'group1',
  'name': 'first',
  'group': [{'_id': 0, 'type': 'int', 'name': 'one', 'des': 1},
   {'_id': 1, 'type': 'int', 'name': 'two', 'des': 2}]},
 {'g_id': 1,
  'type': 'group2',
  'name': 'second',
  'group': [{'_id': 2, 'type': 'int', 'name': 'one', 'des': 1},
   {'_id': 3, 'type': 'int', 'name': 'five', 'des': 5}]}]
Answered By: Deepak Tripathi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.