How can I print out specific key values from nested dict?

Viewed 40

I have some address list with nested dict type like this.

{   'documents': [   {   'address': {   'address_name': '100 Broadway, New York, NY 10005',
                                    'main_address_no': '10005',
                                    'mountain_yn': 'N',
                                    'region_1depth_name': 'New York',
                                    'region_2depth_name': 'Broadway',
                                    'region_3depth_name': '100',
                                    'sub_address_no': '',
                                    'zip_code': ''},
                     'road_address': None}],
'meta': {'total_count': 1}}

and I wonder how can I print out specific value like 'address_name'. I've tried to access with indexing method, but it won't work

1 Answers

Try:

dct = {
    "documents": [
        {
            "address": {
                "address_name": "100 Broadway, New York, NY 10005",
                "main_address_no": "10005",
                "mountain_yn": "N",
                "region_1depth_name": "New York",
                "region_2depth_name": "Broadway",
                "region_3depth_name": "100",
                "sub_address_no": "",
                "zip_code": "",
            },
            "road_address": None,
        }
    ],
    "meta": {"total_count": 1},
}

for document in dct["documents"]:
    print("Address:", document["address"]["address_name"])

Prints:

Address: 100 Broadway, New York, NY 10005
Related