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.
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]]}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With