【发布时间】:2016-04-17 16:15:11
【问题描述】:
假设我有一个这样的字典列表:
[{'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} ... ]
我想将字典合并在一起,以便关键“数量”将是字典中所有 amounts 的总和,其中 account_id_credit 和 account_id_debit 相同,但前提是其中 type 是 @ 987654326@。其他types 应保持原样。
最好的方法是什么?
【问题讨论】:
-
我不明白您如何将这些字典合并在一起。
amount是一个数字字段,因此您可以将这些值相加,但其他字段呢?account_id_debit至少有三个不同的值。您将如何选择其中一个用于合并的字典? -
嗯,就是这样——在一个字典中为 account_id_debit 和 account_id_credit 相同的所有字典中的金额相加。实际上,“名称”可以是任何东西,例如来自第一个 dict 的值。如果你得到我的话,有点像聚合的重复数据删除。
-
你自己尝试过吗?
-
看起来像
pandas.DataFrame和一些groupby的案例
标签: python dictionary merge conditional