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

如何使用字典update方法替代列表传值并理解其多字典场景用法

解决字典update方法在多字典嵌套列表场景中的使用问题

首先,你注释里的update用法有误——字典的update()方法需要接收字典对象作为参数,而不是格式化后的字符串。它的核心作用是把传入字典的键值对合并到原字典中,若存在重复键则会覆盖原有的值。

修正后的代码(使用update方法)

我帮你调整了代码,不仅用上了update,还优化了成本计算和分组逻辑(注意:itertools.groupby要求数据先按分组键排序,否则会出现分组不完整的情况,所以我添加了排序步骤):

from itertools import groupby

def format_account_details(rows):
    # 先按account_id和business_unit排序,确保groupby能正确分组
    sorted_rows = sorted(rows, key=lambda x: (x["account_id"], x["business_unit"]))
    
    result = {}
    total_account_cost = 0
    
    for account_id, account_group in groupby(sorted_rows, key=lambda x: x["account_id"]):
        result[account_id] = {}
        for business_unit, bu_group in groupby(account_group, key=lambda x: x["business_unit"]):
            bu_list = list(bu_group)
            # 直接计算当前业务单元的总成本,累加至总费用
            bu_total = sum(item['total_cost'] for item in bu_list)
            total_account_cost += bu_total
            result[account_id][business_unit] = bu_list
    
    resp = {}
    # 使用update方法一次性合并多个键值对
    resp.update({
        'total_accounts': len(result),
        'total_cost': total_account_cost,
        'aggregates': []
    })
    
    for account_id, bu_dict in result.items():
        for business_unit, items in bu_dict.items():
            # 清理不需要的字段并添加到aggregates
            cleaned_items = [{k: v for k, v in item.items() if k not in ('account_id', 'service_name')} for item in items]
            resp['aggregates'].append({
                "account_id": account_id,
                "business_unit": business_unit,
                "top_utilized": cleaned_items
            })
    
    return resp

# 你的JSON数据
row = { 
    "aggregates": [
        { "services_count": 9, "service_name": "S3", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 0.3200019691, "ytd_spends": 0.3200019691, "account_id": "136981853693" }, 
        { "services_count": 5, "service_name": "RDS", "business_unit": "Customer Service", "last_month_costs": 0, "total_cost": 297.6462777693, "ytd_spends": 297.6462777693, "account_id": "136981853693" }, 
        { "services_count": 38, "service_name": "EBS", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 49.7080945265006, "ytd_spends": 49.7080945265006, "account_id": "136981853693" }, 
        { "services_count": 3, "service_name": "ELB", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 1.5519276537, "ytd_spends": 1.5519276537, "account_id": "136981853693" }, 
        { "services_count": 22, "service_name": "EC2", "business_unit": "IT OPS", "last_month_costs": 0, "total_cost": 442.70678455851, "ytd_spends": 442.70678455851, "account_id": "136981853678" }
    ] 
}

print(format_account_details(row["aggregates"]))

关键说明

  1. update方法的正确使用:
    你原来的注释写法resp.update("total_accounts:{}".format(...))会报错,因为字符串不是字典类型。正确的使用方式有两种:

    # 方式1:单次update多个键值对
    resp.update({
        'key1': value1,
        'key2': value2
    })
    # 方式2:多次单独update单个键值对
    resp.update({'total_accounts': len(result)})
    resp.update({'total_cost': total_account_cost})
    
  2. 嵌套字典与列表的处理:
    分组后我们把每个业务单元的列表存储在result[account_id][business_unit]中,后续清理字段时用列表推导式一次性处理,比循环删除字段更高效简洁。

  3. groupby的注意事项:
    groupby只会将连续相同的键分到同一组,所以必须先对数据按分组键排序,否则如果同一个account_id的记录不连续,会被分成多个独立分组,导致结果错误。

内容的提问来源于stack exchange,提问作者Mayur Potdar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:40:16