Q: Merging a list of dictionaries I have a list of dicts as below.
list = [ {id: 1, s_id:2, class: 'a', teacher: 'b'} ]
list1 = [ {id: 1, c_id:1, rank:2, area: 34}, {id:1, c_id:2, rank:1, area: 21} ]

I want to merge the two lists on the common key-value pairs (in this case 'id:1')
Merged_list = [ {id:1, s_id:2, class: 'a', teacher: 'b', list1: {c_id:1, rank: 2, area: 34}, {c_id:2, rank: 1, area: 21} ]  

How do I go about this?
Thanks

A: You can use
merged_list = [{**d1, **d2} for d1, d2 in zip(list1, list2)]

>>> merged_list
    [{'id': 1, 's_id': 2, 'class': 'a', 'teacher': 'b', 'rank': 2, 'area': 34},
     {'id': 2, 's_id': 3, 'class': 'c', 'teacher': 'd', 'rank': 1, 'area': 21}]

where {**d1, **d2} is just a neat way to combine 2 dictionaries. Keep in mind this will replace the duplicate keys of the first dictionary. If you're on Python 3.9, you could use d1 | d2.
EDIT: For the edit in your question, you can try this horrible one liner (keep in mind this will create the pair list1: [] if no matching indeces were found on list1):
list_ = [{"id": 1, "s_id": 2, "class": 'a', "teacher": 'b'}]
list1 = [{"id": 1, "c_id": 1, "rank": 2, "area": 34}, {"id": 1, "c_id": 2, "rank": 1, "area": 21}]

merged_list = [{**d, **{"list1": [{k: v for k, v in d1.items() if k != "id"} for d1 in list1 if d1["id"] == d["id"]]}} for d in list_]

>>> merged_list
    [{'id': 1,
      's_id': 2,
      'class': 'a',
      'teacher': 'b',
      'list1': [{'c_id': 1, 'rank': 2, 'area': 34},
       {'c_id': 2, 'rank': 1, 'area': 21}]}]

This is equivalent to (with some added benefits):
merged_list = []
for d in list_:
    matched_ids = []
    for d1 in list1:
        if d["id"] == d1["id"]:
            d1.pop("id") # remove id from dictionary before appending
            matched_ids.append(d1)
            
    if matched_ids: # added benefit of not showing the 'list1' key if matched_ids is empty
        found = {"list1": matched_ids}
    else:
        found = {}
        
    merged_list.append({**d, **found})


A: Try this
And don't forget to put " " when declare string
list = [ {"id": 1, "s_id": 2  ," class": 'a', "teacher": 'b'}, {"id": 2, "s_id" : 3, "class" : 'c', "teacher": 'd'} ]
list1 = [ {"id": 1, "rank" :2, "area" : 34}, {"id" :2, "rank" :1, "area": 21} ]

list2 = list1 + list
print(list2)

