我有一个这样的字典列表
[
{
"account_name": "Rounded Off (Purchase)",
"amount": 0.28,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
},
{
"account_name": "Discount (Purchase)",
"amount": 100,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
},
{
"account_name": "Discount (Purchase)",
"amount": 86.4,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
}
]`
我想通过添加"金额"来简化列表。如果两个字典的"doc"值相同和";account_name"关键字,例如本例中的"account_name":折扣(购买)&;和";doc":"P.Inv-1".
我想不出一个简单的解决方案,而不是在列表上使用大量占位符变量和多个循环。
预期的结果应该看起来像
[
{
"account_name": "Rounded Off (Purchase)",
"amount": 0.28,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
},
{
"account_name": "Discount (Purchase)",
"amount": 186.4,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
}
]
非常感谢任何帮助。谢谢。
这通常有助于逐渐思考这些问题,也许使用简单的笔和纸来理解我们的变量将如何随着时间的推移而演变。现在做一点小小的努力,就能在中长期内大有作为。
我的方法是创建一个空列表,每次您的两个键不同时填充该列表。如果它们相同,则更新amount-value。您可能想要决定"data_created"字段,因为现在我根本不检查它(它保留第一个'data_created'值还是第二个?为什么?)既然你没有提供一个可复制的例子,我将这样写:
initial_dictionary_list = [
{
"account_name": "Rounded Off (Purchase)",
"amount": 0.28,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
},
{
"account_name": "Discount (Purchase)",
"amount": 100,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T15:30:42.964203"
},
{
"account_name": "Discount (Purchase)",
"amount": 86.4,
"doc_date": "2023-04-05",
"doc": "P.Inv.-1",
"date_created": "2023-04-05T13:30:42.964203"
}
]
from typing import Dict, List # these provide very helpful type hints
def process_dictionary_list(data: list[dict]) -> list[dict]:
list_of_dictionaries_with_different_keys = {}
for dictionary in dictionary_list:
key = (dictionary['account_name'], dictionary['doc'])
if key in list_of_dictionaries_with_different_keys:
list_of_dictionaries_with_different_keys[key]['amount'] += dictionary['amount']
else:
list_of_dictionaries_with_different_keys[key] = dictionary.copy()
return list(list_of_dictionaries_with_different_keys.values())
final_dictionary_list = process_dictionary_list(initial_dictionary_list)
print(final_dictionary_list)
# [{'account_name': 'Rounded Off (Purchase)', 'amount': 0.28, 'doc_date': '2023-04-05', 'doc': 'P.Inv.-1', 'date_created': '2023-04-05T15:30:42.964203'}, {'account_name': 'Discount (Purchase)', 'amount': 186.4, 'doc_date': '2023-04-05', 'doc': 'P.Inv.-1', 'date_created': '2023-04-05T15:30:42.964203'}]