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

Python中如何从JSON嵌套字典获取labels字段的值?

问题描述

我是Python和JSON新手,目前遇到无法打印嵌套在字典'result'下的'labels'值的问题。

尝试过的代码如下:

for i in data['result']:
    print("Value:", i['value'])

    values = i['value']

    print("X:", values['x'])
    print("Y:", values['y'])
    print("Width:", values['width'])
    print("Height:", values['height'])

上述代码可正常输出x、y等值,但执行print("labels:", values['labels'])时返回KeyError: 'labels'。

执行for item in values: print(item)后,输出的键包含'labels'。

JSON文件结构如下:

{"id": 9,"created_username": "","created_ago": "3\u00a0weeks, 3\u00a0days","completed_by": {"id": 1,"first_name": "","last_name": "","email": ""},"task": {"id": 1,"data": {"image": "/data/upload/2/adf8540d-2-33.png"},"meta": {},"created_at": "2022-11-21T14:52:22.478537Z","updated_at": "2022-11-22T12:51:18.105745Z","is_labeled": true,"overlap": 1,"inner_id": 1,"total_annotations": 1,"cancelled_annotations": 0,"total_predictions": 0,"comment_count": 0,"unresolved_comment_count": 0,"last_comment_updated_at": null,"project": 2,"updated_by": 1,"file_upload": 70,"comment_authors": []},"result": [{"original_width": 512,"original_height": 512,"image_rotation": 0,"value": {"x": 50.898958419872464,"y": 44.0069438675168,"width": 2.397222452993284,"height": 2.0975696463691196,"rotation": 0},"id": "pgaiV8NjWC","from_name": "rect","to_name": "image","type": "rectangle","origin": "manual"},{"original_width": 512,"original_height": 512,"image_rotation": 0,"value": {"x": 50.898958419872464,"y": 44.0069438675168,"width": 2.397222452993284,"height": 2.0975696463691196,"rotation": 0,"labels": ["LM"]},"id": "pgaiV8NjWC","from_name": "labels","to_name": "image","type": "labels","origin": "manual"}],"was_cancelled": false,"ground_truth": false,"created_at": "2022-11-22T12:51:18.001777Z","updated_at": "2022-11-22T12:51:18.001777Z","lead_time": 21.556,"project": 2,"parent_prediction": null,"parent_annotation": null}

请问如何打印出'labels'的值?


解决方案

问题核心:result数组里的元素并非都包含labels键——第一个元素的value字典没有这个键,第二个才有,直接取值会触发KeyError。

方法1:先判断键是否存在

遍历过程中检查labels是否在当前values的键集合中,再决定是否打印:

for i in data['result']:
    values = i['value']
    print("X:", values['x'])
    print("Y:", values['y'])
    print("Width:", values['width'])
    print("Height:", values['height'])
    # 检查labels键是否存在
    if 'labels' in values:
        print("labels:", values['labels'])
    else:
        print("labels: 无")

方法2:使用字典get()方法

get()方法支持指定键不存在时的默认值,避免报错:

for i in data['result']:
    values = i['value']
    print("X:", values['x'])
    print("Y:", values['y'])
    print("Width:", values['width'])
    print("Height:", values['height'])
    # 不存在labels时返回"无",也可以设为None
    print("labels:", values.get('labels', "无"))

你之前执行for item in values: print(item)时看到'labels',是因为循环到第二个result元素时,values里确实有这个键,但第一个元素没有,所以直接取值会在第一次循环就报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:40:41