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

如何更新含列表的嵌套字典元素?Python方法报错求解决方案

解决嵌套字典+混合列表的元素更新问题

原方法报错的核心原因是:路径中的fields对应的数据是列表类型,但原代码用字符串player去索引列表,而列表只能用整数索引,因此抛出TypeError。

解决方案

调整路径格式以支持列表索引,并修改函数的路径解析逻辑,具体如下:

  1. 路径格式规则:用.分割路径,列表元素的位置用数字表示,比如fields.0.player表示取fields列表的第0个元素,再访问其player键。
  2. 修改后的函数:
from functools import reduce
import operator

json_test = {'request_version': 'v1.0',
 'fields': [{'team': [{'name': 'Real Madrid', 'colour': 'white'}],
   'location': {'type': 'Feature',
    'geometry': {'type': 'Point', 'coordinates': [0, 53]}},
   'query': {'filter': '2024/25'},
   'player': 'Bellingham'}]}

def update_attribute(element, json_data, new_value):
    # 解析路径:将数字段转为整数,适配列表索引
    path_segments = []
    for seg in element.split('.'):
        path_segments.append(int(seg) if seg.isdigit() else seg)
    
    *path, last_key = path_segments
    # 遍历路径找到目标父节点
    target_parent = reduce(operator.getitem, path, json_data)
    # 更新目标值
    target_parent[last_key] = new_value
    return json_data

# 示例调用:更新fields列表第0个元素的player字段
updated_json = update_attribute('fields.0.player', json_test, 'Mbappe')
print(updated_json['fields'][0]['player'])  # 输出: Mbappe

# 进阶调用:更新嵌套列表中的元素
update_attribute('fields.0.team.0.name', json_test, 'Barcelona')
print(json_test['fields'][0]['team'][0]['name'])  # 输出: Barcelona

关键修改点

  • 新增路径段类型转换:自动将路径中的数字字符串转为整数,解决列表索引的类型问题
  • 路径格式明确:通过数字标识列表元素位置,让路径能同时兼容字典键和列表索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:55:06