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

嵌套字典存在对应Key却触发KeyError的技术问题求助

解决KeyError问题:字典键类型不匹配

问题分析

你遇到的KeyError: '7'核心原因是字典data的顶层键是整数类型,但你代码里误用字符串类型去访问它。

先看你的data定义:

data = {0: {}, 1: {'1': 'M_AVL_002'}, 2: {'2': 'CloudServiceAvailability'}, ..., 7: {'4': ' 100 x (P_001- M_TQD_001)/P_001'}, ...}

所有顶层键都是整数(0,1,2,...7...),但在赋值变量b时你写了:

b=str(data[str(int(row)+1)][str(int(col)+1)])

这里str(int(row)+1)把计算出的整数7转成了字符串'7',然后用data['7']去访问——可字典里根本没有字符串键'7',自然触发KeyError。你说的“键存在”是对的,但指的是整数键7,不是字符串'7'。

解决方案

核心修改是:访问data顶层时用整数索引,去掉多余的str()转换。内层子字典的键是字符串(比如{'4': 'xxx'}里的'4'),所以str(int(col)+1)是正确的,不用改。

关键代码修正

把报错行的str(int(row)+1)改成int(row)+1,比如:

# 处理E开头的场景
metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression').set("expressionStatement",str(data[int(row)+1][str(int(col)+1)]))

# 处理P开头的场景
b=str(data[int(row)+1][str(int(col)+1)])
c=str(data[int(row)+2][str(int(col)+1)])

可读性优化版完整代码

我还做了一些代码简洁性和性能优化,避免重复计算和节点查找:

for metric in XML.findall("{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Metric"):
    for row, value in data.items():
        if row == 0:
            continue  # 用continue替代pass,逻辑更清晰
        for col, v in value.items():
            if col == "1":
                metric.set('id', v)  # 直接用遍历得到的v,不用重复访问data[row][col]
            elif col == "2":
                metric.set('description', v)
            elif col == "3":
                current_id = v
                col_plus_1 = str(int(col) + 1)  # 提前计算一次,避免重复转换
                if current_id.startswith("E"):
                    # 提前获取Expression节点,避免重复查找XML
                    expr_node = metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression')
                    expr_node.set("id", current_id)
                    expr_node.set("expressionStatement", data[row+1][col_plus_1])
                    expr_node.set("expressionLanguage", data[row+2][col_plus_1])
                    expr_node.set("unit", data[row+3][col_plus_1])
                elif current_id.startswith("P"):
                    for param in metric.findall('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Parameter'):
                        if param.get('id') == current_id:
                            param.set("id", current_id)
                            param.set("parameterStatement", data[row+1][col_plus_1])
                            param.set("unit", data[row+2][col_plus_1])
                elif current_id.startswith("R"):
                    for rule in metric.findall('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Rule'):
                        if rule.get('id') == current_id:
                            rule.set("id", current_id)
                            rule.set("ruleStatement", data[row+1][col_plus_1])

验证测试

针对你提到的报错场景row=6、col=3:

  • row+1得到整数7,data[7]能正确访问到{'4': ' 100 x (P_001- M_TQD_001)/P_001'}
  • col_plus_1是字符串'4',data[7]['4']可以顺利拿到对应值,不会再触发KeyError

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:13:32