Home > OS >  How can I convert a list of dictionaries into another dictionaries with exchanging key value in pyht
How can I convert a list of dictionaries into another dictionaries with exchanging key value in pyht

Time:09-20

I have the following list of dictionaries:

[
    {"id": 1, "roll_id": ["101", "201"]},
    {"id": 2, "roll_id": ["301", "201"]},
    {"id": 3, "roll_id": ["424"]}
]

Now I need to convert this into the following format:

[
    {'roll_id': '101', 'id':["1"]},
    {'roll_id': '201', 'id':["1","2"]}, 
    {'roll_id': '301', 'id':["2"]},
    {'roll_id': '424', 'id':["3"]}
]

Can anyone help me, please?

CodePudding user response:

You can use a dictionary setdefault to collect the values, then convert to list:

out = {}
for d in l:
    for RID in d['roll_id']:
        out.setdefault(RID, {'roll_id': RID, 'id': []})['id'].append(d['id'])

out = list(out.values())

Another solution using :

l = [
    {"id": 1, "roll_id": ["101", "201"]},
    {"id": 2, "roll_id": ["301", "201"]},
    {"id": 3, "roll_id": ["424"]}
]

import pandas as pd
out = (pd
   .json_normalize(l)
   .explode('roll_id')
   .groupby('roll_id', as_index=False)
   ['id'].agg(list)
   .to_dict('records')
 )

Output:

[{'roll_id': '101', 'id': [1]},
 {'roll_id': '201', 'id': [1, 2]},
 {'roll_id': '301', 'id': [2]},
 {'roll_id': '424', 'id': [3]}]

CodePudding user response:

Maybe this article could help you

CodePudding user response:

Try this:

data = [{"id": 1, "roll_id": ["101", "201"]}, {"id": 2, "roll_id": ["301", "201"]}, {"id": 3, "roll_id": ["424"]}]
res = []
for el in data:
    for r in el["roll_id"]:
        find = [i for i, v in enumerate(res) if v['roll_id'] == r]
        if not find:
            res.append({'roll_id': r, "id": [el['id']]})
        else:
            res[find[0]]['id'].append(el['id'])['id'].append(el['id'])

print(res)

Result:

[{'roll_id': '101', 'id': [1]}, {'roll_id': '201', 'id': [1, 2]}, {'roll_id': '301', 'id': [2]}, {'roll_id': '424', 'id': [3]}]

Not my best but it work.

Regards,

CodePudding user response:

I think the most efficient way of doing it could look something like this:

def convert(input_dict):
    result = {}
    for dic in input_dict:
        for roll_id in dic["roll_id"]:
            str_id = str(dic["id"])
            if roll_id in result:
                result[roll_id]["id"].append(str_id)
            else:
                result[roll_id] = {"roll_id":roll_id, "id":[str_id]}
    return [result[i] for i in result]

print(convert(test))
  • Related