如何从嵌套的字典中打印出特定的键值?

时间:2021-07-14 05:47:14

标签: dictionary printing nested

我有一些像这样嵌套字典类型的地址列表。

{   '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}}

我想知道如何打印出像“address_name”这样的特定值。 我尝试使用索引方法访问,但它不起作用

1 个答案:

答案 0 :(得分:0)

试试:

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"])

打印:

Address: 100 Broadway, New York, NY 10005