【问题标题】:Python - accessing a value within in a nested dictionary within a listPython - 访问列表中嵌套字典中的值
【发布时间】:2018-10-17 18:50:27
【问题描述】:

我有一个如下所示的 JSON API 响应:

json_data=

{
    "sales_list": [
        {
            "date": "all",
            "country": "all",
            "units": {
                "product": {
                    "promotions": 0,
                    "downloads": 1,
                    "updates": 2,
                    "refunds": 3
                },
                "iap": {
                    "promotions": 0,
                    "sales": 0,
                    "refunds": 0
                }
            },
            "revenue": {
                "product": {
                    "promotions": "0.00",
                    "downloads": "0.00",
                    "updates": "0.00",
                    "refunds": "0.00"
                },
                "iap": {
                    "promotions": "0.00",
                    "sales": "0.00",
                    "refunds": "0.00"
                },
                "ad": "0.00"
            }
        }
    ],
    "next_page": null,
    "code": 200,
    "prev_page": null,
    "vertical": "apps",
    "page_num": 1,
    "iap_sales_list": [],
    "currency": "USD",
    "page_index": 0,
    "market": "ios"
}

我正在使用 Python 并尝试访问响应中的第一个“下载”值。所以我需要从sales_list(字典中的列表)>单位(字典)>产品(字典)>下载。我如何开始挖掘这些多层来访问这个单一的值?

我看到了有关访问列表中的字典或嵌套字典中的值的问题。但是对于如何在字典中的列表和列表中的字典之间导航,我有点困惑。任何帮助将不胜感激。

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    类似问题:Python Accessing Nested JSON Data

    这是你需要的吗?

    print(json_data['sales_list'][0]['units']['product']['downloads'])   
    

    它给出输出1

    回答你的问题:
    如您所见,您的 json 字段 sales_list 是字典的单元素列表
    [ {dictionary with field you need}, {other dict}, .. ]
    因此,您需要指定要访问的列表元素的索引 - 如果是单元素列表,它将是 [0],因为列表的第一个元素包含您需要的字段

    【讨论】:

    • 是的,这很有帮助——我一直在使用json_data['sales_list']['units']['product']['downloads'],没有[0]。该组件的作用是什么?
    • 你指的是哪个组件函数?
    • 也就是说,为什么需要指定[0]?它有什么作用?
    • 是的,这是有道理的。感谢您花时间解释!
    【解决方案2】:
    >>> dict['sales_list'][0]['units']['products']['downloads']
    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多