gpt4 book ai didi

Python:根据多个值+总和合并n个字典

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:06 24 4
gpt4 key购买 nike

假设我有一个这样的字典列表:

[{'amount': 42140.0, 'name': 'Payment', 'account_id_credit': 385, 'type': u'expense', 'account_id_debit': 476}, 
{'amount': 43926.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'payable', 'account_id_debit': 641},
{'amount': 3800.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476},
{'amount': 46330.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476},
{'amount': 67357.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'payable', 'account_id_debit': 323},
{'amount': 26441.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476} ... ]

我想将字典合并在一起,这样键“金额”将是字典中所有 金额 的总和,其中 account_id_creditaccount_id_debit 是相同的,但前提是那些的 typeexpense。其他类型应该保持原样。

最好的方法是什么?

最佳答案

一种方法是创建一个中间字典,由 (account_id_credit, account_id_debit) 的元组和总金额值组成的元组作为键,然后从中构建聚合字典列表:

ld = [{'amount': 42140.0, 'name': 'Payment', 'account_id_credit': 385, 'type': u'expense', 'account_id_debit': 476}, 
{'amount': 43926.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'payable', 'account_id_debit': 641},
{'amount': 3800.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476},
{'amount': 46330.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476},
{'amount': 67357.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'payable', 'account_id_debit': 323},
{'amount': 26441.0, 'name': 'Payment', 'account_id_credit': 695, 'type': u'expense', 'account_id_debit': 476} ]


d2 = {}
for d in ld:
if d['type'] != 'expense':
continue
k = (d['account_id_credit'], d['account_id_debit'])
try:
d2[k] += d['amount']
except KeyError:
d2[k] = d['amount']

ld2 = []
for d in ld:
if d['type'] != 'expense':
ld2.append(d)
continue
k = (d['account_id_credit'], d['account_id_debit'])
try:
d['amount'] = d2[k]
# We're done with this amount sum: remove it from the intermediate dict
del d2[k]
except KeyError:
continue
ld2.append(d)
print ld2

[{'account_id_credit': 385, 'account_id_debit': 476, 'amount': 42140.0, 'type': u'expense', 'name': 'Payment'},
{'account_id_credit': 695, 'account_id_debit': 641, 'amount': 43926.0, 'type': u'payable', 'name': 'Payment'},
{'account_id_credit': 695, 'account_id_debit': 476, 'amount': 76571.0, 'type': u'expense', 'name': 'Payment'},
{'account_id_credit': 695, 'account_id_debit': 323, 'amount': 67357.0, 'type': u'payable', 'name': 'Payment'}]

关于Python:根据多个值+总和合并n个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34753981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com