2017-04-05 21 views
-1

我有字典Python列表串連基於特定的價值

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

請更多明確你想要達到的目標並告訴我們你試過的東西 – FLab

+0

另外,你可以使用熊貓嗎?它看起來像這個正確的工具 – FLab

回答

0

你的輸出是不正確的,你想擁有它裏面列表的字典,但你可以有這樣的事情:

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}]]