用列表的嵌套字典解析字典

时间:2019-05-31 19:54:55

标签: python

我正在尝试解析以下字典

{'IsTruncated': False,
    'MaxItems': '100',
    'ResourceRecordSets': [{'Name': 'test.com.',
        {'Name': '1.test.com.',
        'ResourceRecords': [{'Value': '10.0.0.1'}],
        {'Name': '2.test.com.',
        'ResourceRecords': [{'Value': '10.0.0.2'}],
}

我正在寻找的输出是:

1.test.com    10.0.0.1
2.test.com    10.0.0.2

我尝试过:

for resource in response['ResourceRecordSets']:
    print("{}  {}".format(resource['Name'], resource['ResourceRecords'] ))

for resource in response['ResourceRecordSets']:
    print("{}  {}".format(resource['Name'], resource['ResourceRecords'][0] ))

是否有一种简单的方法来访问嵌套列表中的此dict键/值?

1 个答案:

答案 0 :(得分:0)

假设您的字典应如下所示:

{'IsTruncated': False,
'MaxItems': '100',
'ResourceRecordSets': [
    {'Name': 'test.com.', 
    'ResourceRecords' : [{'Value' : '<mising ip addr>'}]},
    {'Name': '1.test.com.',
    'ResourceRecords': [{'Value': '10.0.0.1'}]},
    {'Name': '2.test.com.',
    'ResourceRecords': [{'Value': '10.0.0.2'}]},
    ]

尝试一下:

for resource in response['ResourceRecordSets']:
    print("{}  {}".format(resource['Name'], resource['ResourceRecords'][0]['Value']))