Python:根据几个值+ sum合并n-dictionaries

Mar*_*der 1 python merge conditional dictionary

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

[{'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} ... ]
Run Code Online (Sandbox Code Playgroud)

我想将字典合并在一起,以便关键的"金额"将是所有amounts字典的总和,其中account_id_creditaccount_id_debit是相同的,但只有type这些是expense.其他types应该保持原样.

最好的方法是什么?

xnx*_*xnx 5

一种方法是创建一个中间字典,由具有(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'}]
Run Code Online (Sandbox Code Playgroud)