问题
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.
回答1:
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 parsed_list.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]]}]
回答2:
One way is to use itertools.groupby()
:
from itertools import groupby
print([{"name": key, "data": [(g['date'], g['price']) for g in group]}
for key, group in groupby(my_list, lambda x: x['name'])])
#[{'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)]}]
The first argument to groupby
is an iterable, in this case my_list
.
The second argument is a function that defines how to create the groups, in this case you extract the key name
.
Note: this will group consecutive items with the same name
, so it assumes that my_list
is already sorted with respect to name. If not you can sort first using:
my_list = sorted(my_list, key=lambda x: x['name'])
Then we can iterate over all the (key, group)
pairs from the output of groupby()
and do a list comprehension.
Inside the list comprehension, we do a dict comprehension {"name": key, "data": [(g['date'], g['price']) for g in group]}
to build a dictionary of the form {'name': key, 'data': [[date,price]]}
for each name
.
来源:https://stackoverflow.com/questions/50491984/iterate-over-list-of-dict-and-group-item-by-key