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

Python中从嵌套字典提取指定键数据报错,求解决方案

问题:从嵌套字典提取数据时遇到AttributeError错误

需求描述

  • 待提取的嵌套字典数据:
"defaultKit": {
    "options": {
        "size": "Med/32",
        "color": "blue/green"
    },
    "part": "MK78Z62"
}
  • 期望输出:
size: Med/32
color: blue/green
part: MK78Z62

错误代码及报错

用户编写的代码:

data2 = json.loads(data2)
for item in data2['defaultKit']:
    for key, value in items.items():
        print(f'{key1}: {value1}')

运行后报错:

for key, value in item.items():
                      ^^^^^^^^^^
AttributeError: 'str' object has no attribute 'items'

问题分析与解决

问题原因

遍历data2['defaultKit']时,默认只会遍历字典的键(字符串类型,比如"options"、"part"),所以item是字符串,自然没有items()方法,触发报错。此外代码还存在变量名错误:items应为item,key1、value1应为key、value。

修正后的代码

需要区分defaultKit中的普通键值对和嵌套字典(options),分别处理:

import json

# 假设data2是包含defaultKit的完整JSON字符串
data2 = '''{
    "defaultKit": {
        "options": {
            "size": "Med/32",
            "color": "blue/green"
        },
        "part": "MK78Z62"
    }
}'''

data2 = json.loads(data2)
default_kit = data2['defaultKit']

# 遍历defaultKit的每个键值对
for key, value in default_kit.items():
    # 如果值是嵌套字典,遍历内部键值对
    if isinstance(value, dict):
        for sub_key, sub_value in value.items():
            print(f'{sub_key}: {sub_value}')
    # 普通值直接打印
    else:
        print(f'{key}: {value}')

运行结果

size: Med/32
color: blue/green
part: MK78Z62

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:38:11