简体   繁体   中英

How do I get the value of a dict item within a list, within a dict?

How do I get the value of a dict item within a list, within a dict in Python? Please see the following code for an example of what I mean.

I use the following lines of code in Python to get data from an API.

res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()

data then returns the following Python dictionary:

{
    '_links': {
        'next': {
            'href': null
        },
        'previous': {
            "href": null
        },
        'self': {
            'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/'
        }
    },
    'count': 1,
    'results': [
        {
            '_display': 'Maple Street 99',
            '_links': {
                'self': {
                    'href': 'https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/XXXXXXXXXXXXXXXX/'
                }
            },
            'dataset': 'bag',
            'landelijk_id': 'XXXXXXXXXXXXXXXX',
            'type_adres': 'Hoofdadres',
            'vbo_status': 'Verblijfsobject in gebruik'
        }
    ]
}

Using Python, how do I get the value for 'landelijk_id' , represented by the twelve Xs?

This should work:

>>> data['results'][0]['landelijk_id']
"XXXXXXXXXXXXXXXX"

You can just chain those [] for each child you need to access.

I'd recommend using the jmespath package to make handling nested Dictionaries easier. https://pypi.org/project/jmespath/

import jmespath 
import requests 

res = requests.get('https://api.data.amsterdam.nl/bag/v1.1/nummeraanduiding/', params)
data = res.json()

print(jmespath.search('results[].landelijk_id', data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM