Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over list of dict and group item by key

I have a list of dicts:

my_list = [
    {'name': 'AAA', 'date': '2018-05-14', 'price': 20.0},
    {'name': 'AAA', 'date': '2018-05-15', 'price': 22.0},
    {'name': 'AAA', 'date': '2018-05-16', 'price': 30.0},
    {'name': 'BBB', 'date': '2018-05-14', 'price': 15.0},
    {'name': 'BBB', 'date': '2018-05-15', 'price': 32.0}
    ]

My question is how can I iterate over that list to produce a list in this format?

parsed_list = [
    {'name': 'AAA', 'data': [['2018-05-14', 20.0], ['2018-05-15', 22.0], ['2018-05-16', 30.0]]},
    {'name': 'BBB', 'data': [['2018-05-14', 15.0], ['2018-05-15', 32.0]]}
    ]

I tried approach described in this question: Python: group list items in a dict but I need a different output format and I can't figure out what I need to change.

like image 628
Vlad Avatar asked Dec 03 '22 20:12

Vlad


1 Answers

One way may be to use defaultdict:

from collections import defaultdict

my_list = [
    {'name': 'AAA', 'date': '2018-05-14', 'price': 20.0},
    {'name': 'AAA', 'date': '2018-05-15', 'price': 22.0},
    {'name': 'AAA', 'date': '2018-05-16', 'price': 30.0},
    {'name': 'BBB', 'date': '2018-05-14', 'price': 15.0},
    {'name': 'BBB', 'date': '2018-05-15', 'price': 32.0}
    ]

tmp = defaultdict(list)

for item in my_list:
    tmp[item['name']].append([item['date'],item['price']])
    
parsed_list = [{'name':k, 'data':v} for k,v in tmp.items()]
print(parsed_list)

Result:

[{'name': 'AAA', 'data': [['2018-05-14', 20.0], 
                          ['2018-05-15', 22.0], ['2018-05-16', 30.0]]}, 
 {'name': 'BBB', 'data': [['2018-05-14', 15.0], ['2018-05-15', 32.0]]}]
like image 104
student Avatar answered Dec 14 '22 23:12

student