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

Python中访问嵌套字典方法及JSON字典转Python字典教程

1. 如何在Python中访问嵌套字典

嵌套字典(包括字典里套字典、甚至字典里套列表的情况)访问起来其实很直观,核心就是逐层用键/下标索引,我给你整理几个实用的方法:

  • 直接逐层索引(确定键存在时用):
    比如针对你提供的示例字典,要访问第一个action的value,就先取actions列表,再取列表的第0个元素,最后取value键:

    # 输出第一个action的value值
    print(dictionary["actions"][0]["value"])  # 结果是 "1"
    

    如果是纯嵌套字典(没有列表),比如{"a": {"b": 1}},直接用dict["a"]["b"]就能拿到1。

  • 用get()方法避免KeyError:
    要是不确定某个键/下标是否存在,直接索引会报错,get()可以帮你指定默认值,避免崩溃:

    # 尝试访问不存在的键,返回指定的默认值
    print(dictionary.get("actions", []).get(0, {}).get("non_existent_key", "找不到这个值哦"))
    
  • try-except捕获异常(精细错误处理):
    如果需要针对不同错误做不同处理,用try-except块更灵活:

    try:
        target_value = dictionary["actions"][5]["value"]
    except (KeyError, IndexError) as e:
        print(f"访问出错啦:{e}")
        target_value = "默认值"
    
2. 将给定JSON格式转换为Python字典

你提供的JSON结构和Python字典的语法几乎完全一致,只需要直接调整成Python可识别的写法就行:

dictionary = { 
    "actions": [ 
        { "action_type": "comment", "value": "1" }, 
        { "action_type": "like", "value": "18" }, 
        { "action_type": "post", "value": "4" }, 
        { "action_type": "post_reaction", "value": "268" }, 
        { "action_type": "video_view", "value": "198245" }, 
        { "action_type": "page_engagement", "value": "198536" }, 
        { "action_type": "post_engagement", "value": "198518" } 
    ], 
    "date_start": "2018-..."
}

如果这个JSON是来自字符串(比如从文件、API接口获取的),可以用Python内置的json模块转换:

import json

# 假设json_str是你的JSON格式字符串
json_str = '''{ 
"actions": [ 
{ "action_type": "comment", "value": "1" }, 
{ "action_type": "like", "value": "18" }, 
{ "action_type": "post", "value": "4" }, 
{ "action_type": "post_reaction", "value": "268" }, 
{ "action_type": "video_view", "value": "198245" }, 
{ "action_type": "page_engagement", "value": "198536" }, 
{ "action_type": "post_engagement", "value": "198518" } 
], 
"date_start": "2018-..."
}'''

# 转换为Python字典
dictionary = json.loads(json_str)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:20:07