python-3.x - 对字典值求和,使用两个键作为索引 : how to achieve this?

标签 python-3.x list dictionary indexing key

我有以下字典:

res = [{'name': 'mfi', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0}, 
{'name': 'serv', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0}, 
{'name': 'inv', 'percentage': 100.0, 'tax_base': 1200.0, 'tax_amount': 168.0}, 
{'name': 'mfi', 'percentage': 50.0, 'tax_base': 1500.0, 'tax_amount': 210.0}, 
{'name': 'none', 'percentage': 0.0, 'tax_base': 1000.0, 'tax_amount': 0.0}, 
{'name': 'none', 'percentage': 0.0, 'tax_base': 900.0, 'tax_amount': 126.0}, 
{'name': 'mfi', 'percentage': 50.0, 'tax_base': 1000.0, 'tax_amount': 140.0}]

从这本字典中,我需要对“tax_base”和“tax_amount”值键求和,并使用键“name”和“percentage”作为索引。

因此,我需要:

res_final = [{'name': 'mfi', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0},
{'name': 'mfi', 'percentage': 50.0, 'tax_base': 2500.0, 'tax_amount': 350.0},  
{'name': 'serv', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0}, 
{'name': 'inv', 'percentage': 100.0, 'tax_base': 1200.0, 'tax_amount': 168.0}, 
{'name': 'none', 'percentage': 0.0, 'tax_base': 1900.0, 'tax_amount': 126.0}, 
]

我怎样才能做到这一点?你能给我一个 sample 吗?

最佳答案

采用您的原始输入 res 和您的首选输出 res_final,以下代码将起作用:

# Creating a temporary dictionary with the aggregation
temp_result = {}
for each in res:
    key = (each['name'], each['percentage'])
    if key not in temp_result:
        temp_result[key] = dict(tax_base=0, tax_amount=0)

    temp_result[key]['tax_base'] += each['tax_base']
    temp_result[key]['tax_amount'] += each['tax_amount']

# Transforming the temporary dictionary to the correct format
final_result = []
for (name, percentage), taxes in temp_result.items():
    final_result.append(dict(
            name=name,
            percentage=percentage,
            tax_base=taxes['tax_base'],
            tax_amount=taxes['tax_amount']
    ))

for each in final_result:
    print(each)

结果将是:

{'name': 'mfi', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0}
{'name': 'serv', 'percentage': 100.0, 'tax_base': 1000.0, 'tax_amount': 140.0}
{'name': 'inv', 'percentage': 100.0, 'tax_base': 1200.0, 'tax_amount': 168.0}
{'name': 'mfi', 'percentage': 50.0, 'tax_base': 2500.0, 'tax_amount': 350.0}
{'name': 'none', 'percentage': 0.0, 'tax_base': 1900.0, 'tax_amount': 126.0}

说明

在第一部分中,我们创建了一个新字典,它以 namepercentage 的组合作为 tuple 的键,作为使用 tax_basetax_amount 为该键赋值字典。

然后我们检查键是否已经在我们的字典中,如果不在我们创建键。最后一步是对 tax_basetax_amount 求和。

现在我们有一本包含所有信息的字典,但格式不正确。第二部分负责这一点。我们再次将键拆分为 namepercentage 并将数据与 tax_basetax_amount 合并到一个字典中。


编辑

如果人们想知道如何使用 pd.DataFrame 来做到这一点。

import pandas as pd

df = pd.DataFrame(res)
res = df.groupby(['name', 'percentage'], as_index=False).sum()
final_result = res.to_dict('records')

for each in final_result:
    print(each)

将产生相同的输出,但不保证与输入的顺序相同。

关于python-3.x - 对字典值求和,使用两个键作为索引 : how to achieve this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66411153/

相关文章:

r - 将元素添加到 R 中的列表(在嵌套列表中)

javascript - d3.js悬停在 map 上不显示文本框,css问题

python - 如何在类中迭代 `dict` 就像只引用 `dict` 一样?

swift - 如何在 Swift 中更新字典值

Python 3 逻辑 not 将 True 返回为 True

python - python3 nltk word_tokenize() 有字符串长度限制吗?

Python逆向模式

python - 如何让 discord 机器人在 x 分钟不活动后离开语音 channel ?

python 3.6 : Moving around words within a string

python - 如何测试类型为 'int' 的列表中的每一项?