Home > Software engineering >  Reformatting list of dictionaries for a specific output (explained in question)
Reformatting list of dictionaries for a specific output (explained in question)

Time:08-03

I have a list of dictionaries as below:

[{'storeid':2, 'productid':4},{'storeid':1, 'productid':1},{'storeid':1, 'productid':2}]

How to create a new list of dictionary as follows, from above one?

[{'storeid':2, 'productid':[4]}, {'storeid':1, 'productid':[1,2]}]

By using the following code, got the expected result. But I have used multiple for loops, dicts and lists to achieve this. Is there any efficient way to achieve this?

input_data = [{'storeid':2, 'productid':4}, {'storeid':1, 'productid':1}, 
              {'storeid':1, 'productid':2}]

unique_store_id_list = []  ##[2,1]
for ids in input_data:
    if ids['storeid'] not in unique_store_id_list:
        unique_store_id_list.append(ids['storeid'])

final_lst = []  ##[{'storeid':2, 'productid':[4]}, {'storeid':1, 'productid':[1,2]}]
for store_id in unique_store_id_list:
    final_dic = {}
    product_id_lst = []
    for elem in input_data:
        if elem['storeid'] == store_id:
            product_id_lst.append(elem['productid'])
    final_dic['storeid'] = store_id
    final_dic['productid'] = product_id_lst
    final_lst.append(final_dic)

CodePudding user response:

There's probably some neater python dict comprehensions that could be done, but to get it to a more idiomatic way you can use:

input_data = [
    {'storeid': 2, 'productid': 4},
    {'storeid': 1, 'productid': 1},
    {'storeid': 1, 'productid': 2}]

output_data = []

for obj in input_data.copy():
    output_data.append({'storeid': obj['storeid'], 'productid': [
                       x['productid'] for x in input_data if x['storeid'] == obj['storeid']]})

print(list({v['storeid']:v for v in output_data}.values()))

CodePudding user response:

You can do it in one line with pandas:

import pandas as pd
data = [{'storeid':2, 'productid':4},{'storeid':1, 'productid':1},{'storeid':1, 'productid':2}]

final_list = pd.DataFrame(data).groupby('storeid', as_index=False).agg(list).to_dict(orient='records')

Output:

[{'storeid': 1, 'productid': [1, 2]}, {'storeid': 2, 'productid': [4]}]

CodePudding user response:

Another solution:

lst = [
    {"storeid": 2, "productid": 4},
    {"storeid": 1, "productid": 1},
    {"storeid": 1, "productid": 2},
]

out = {}
for d in lst:
    out.setdefault(d["storeid"], []).append(d["productid"])

out = [{"storeid": k, "productid": v} for k, v in out.items()]
print(out)

Prints:

[{"storeid": 2, "productid": [4]}, {"storeid": 1, "productid": [1, 2]}]
  • Related