Python-访问列表内嵌套字典中的值 [英] Python - accessing a value within in a nested dictionary within a list

查看:113
本文介绍了Python-访问列表内嵌套字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下内容的JSON API响应:

I have a JSON API response that looks like the following:

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(字典中的列表)>单位(字典)>产品(字典)>下载开始.我该如何挖掘这些多层以仅访问该单个值?

I'm using Python and am trying to access the first "downloads" value in the response. So I need to go from sales_list (list in a dict) > units (dict) > product (dict) > downloads. How to I got about digging down these multiple layers to access just this single value?

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

I've seen questions about accessing values within a dictionary within a list, or within a nested dictionary. But I'm a little confused as to how to navigate between/among lists in dictionaries and dictionaries in lists. Any help would be greatly appreciated.

推荐答案

类似的问题: Python访问嵌套的JSON数据

这就是您需要的吗?

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

它给出输出 1

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

to answer your question:
as you see your json field sales_list is one-element list of dictionaries
[ {dictionary with field you need}, {other dict}, .. ]
because of that you need to specify index of list element you want to acces - in case of your one-element list it will be [0] because first element of your list contains field you need

这篇关于Python-访问列表内嵌套字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆