Python - accessing a value within in a nested dictionary within a list

♀尐吖头ヾ 提交于 2021-02-17 05:40:21

问题


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"
}

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.


回答1:


similiar question: Python Accessing Nested JSON Data

is that what you need?

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

it gives output 1

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




回答2:


>>> dict['sales_list'][0]['units']['products']['downloads']
1


来源:https://stackoverflow.com/questions/52861717/python-accessing-a-value-within-in-a-nested-dictionary-within-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!