Py学习  »  Python

有没有办法在python字典和列表中对值进行分组?

asd-qwert • 3 年前 • 1270 次点击  

我目前有一个类似以下内容的值列表:

lst = [{'Amount': 13.5, 'Name': 'Amy', 'date': '2022-01-30'}, 
{'Amount': 15, 'Name': 'Bob', 'date': '2022-01-30'}, 
{'Amount': 13.5, 'Name': 'Cara', 'date': '2022-01-31'}]

我如何按日期分组?

[{'date': '2022-01-30', 'details': [{'Amount': 13.5, 'Name': 'Amy'}, {'Amount': 15, 'Name': 'Bob'}]},
{'date': '2022-01-31', 'details': [{'Amount': 13.5, 'Name': 'Cara'}]

我试过用for loop做些什么,但似乎对我不起作用

final_data = []

for i in lst:
    temp_data = {}
    if i['date'] not in temp_data:
        temp_data['date'] = i['date']
        final_data.append(temp_data)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130533
 
1270 次点击  
文章 [ 2 ]  |  最新文章 3 年前