You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对嵌套Python字典中的数值列进行求和?

问题描述

我有一个如下格式的嵌套Python字典:

{
    '1000': {
        'owner_id':'1000',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    },
    '1084': {
        'owner_id':'10084',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    }
}

需要得到如下格式的求和结果(自动对数值型字段求和,无需逐个指定键):

{
    'in_hours':200,
    'us_hours':400,
    'total_revenue':200
}

请问该如何实现?

解决方案

下面提供几种无需逐个指定键的实现方式:

方法一:基础循环自动识别数值字段

通过遍历所有子字典,只对int或float类型的字段进行累加,自动跳过字符串类型的owner_id:

original_data = {
    '1000': {
        'owner_id':'1000',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    },
    '1084': {
        'owner_id':'10084',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    }
}

sum_result = {}
for sub_dict in original_data.values():
    for key, value in sub_dict.items():
        if isinstance(value, (int, float)):
            sum_result[key] = sum_result.get(key, 0) + value

print(sum_result)

这里用sum_result.get(key, 0)简化了判断键是否存在的逻辑,代码更紧凑。

方法二:用collections.defaultdict简化累加逻辑

借助defaultdict自动为新键初始化默认值0,省去手动判断的步骤:

from collections import defaultdict

original_data = {
    '1000': {
        'owner_id':'1000',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    },
    '1084': {
        'owner_id':'10084',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    }
}

sum_result = defaultdict(int)
for sub_dict in original_data.values():
    for key, value in sub_dict.items():
        if isinstance(value, (int, float)):
            sum_result[key] += value

# 可选:转换为普通字典
sum_result = dict(sum_result)
print(sum_result)

方法三:用pandas快速处理大规模数据

如果你的数据量较大,用pandas可以更高效地自动筛选数值列并求和:

import pandas as pd

original_data = {
    '1000': {
        'owner_id':'1000',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    },
    '1084': {
        'owner_id':'10084',
        'in_hours':100,
        'us_hours':200,
        'total_revenue':100
    }
}

df = pd.DataFrame.from_dict(original_data, orient='index')
# 筛选数值类型列并求和,再转为字典
sum_result = df.select_dtypes(include=['int64', 'float64']).sum().to_dict()

print(sum_result)

内容的提问来源于stack exchange,提问作者Happy Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 02:10:36