我有一个字典列表
list_dict=[{'date':'24-01-2017','amount':12.0},{'date':'24-01-2017','amount':23.0},
{'date':'24-01-2017','amount':2.0},{'date':'25-01-2017','amount':10.0},{'date':'25-01-2017','amount':3.0},
{'date':'26-01-2017','amount':2.0}]
我需要像
这样的输出new_dict=[{'total':27.0,[{'date':'24-01-2017','amount':12.0},{'date':'24-01-2017','amount':23.0},
{'date':'24-01-2017','amount':2.0},],[{'total':13.0,{'date':'25-01-2017','amount':10.0},{'date':'25-01-2017','amount':3.0}],[{'total':2.0,
{'date':'26-01-2017','amount':2.0}]]
如何在python中执行此操作?
答案 0 :(得分:0)
您的输出不正确,因为您想要一个包含列表的dict,但您可以这样:
dates = list(set([item['date'] for item in list_dict]))
result = [[{'total': sum([item['amount'] for item in list_dict if item['date'] == date])}, [{k: v} for value in list_dict for k, v in value.items() if value['date'] == date]] for date in dates]
结果将如下所示:
[{'total': 13.0}, [{'date': '25-01-2017'}, {'amount': 10.0}, {'date': '25-01-2017'}, {'amount': 3.0}]]
[{'total': 37.0}, [{'date': '24-01-2017'}, {'amount': 12.0}, {'date': '24-01-2017'}, {'amount': 23.0}, {'date': '24-01-2017'}, {'amount': 2.0}]]
[{'total': 2.0}, [{'date': '26-01-2017'}, {'amount': 2.0}]]