繁体   English   中英

从嵌套字典中提取值

[英]Extracting value from a nested dict

我正在尝试从嵌套字典中提取一个值,如下所示:

response = 
    {'TransitGatewayRouteTables': [{'TransitGatewayRouteTableId': 'tgw-rtb-0461b603f87a09881',
                                            'TransitGatewayId': 'tgw-0d79045d0f874bfd4',
                                            'State': 'available', 
                                            'DefaultAssociationRouteTable': False, 
                                            'DefaultPropagationRouteTable': True, 
                                            'CreationTime': datetime.datetime(2020, 6, 18, 2, 32, 25,
        tzinfo=tzlocal()),
                                            'Tags': []}], 
             'ResponseMetadata': {'RequestId': '8d427b26-7735-4154-a7a3-ed45c83b5894',
                                  'HTTPStatusCode': 200, 
                                  'HTTPHeaders': {'x-amzn-requestid': '8d427b26-7735-4154-a7a3-ed45c83b5894',
                                                  'content-type': 'text/xml;charset=UTF-8', 
                                                  'transfer-encoding': 'chunked', 
                                                  'vary': 'accept-encoding', 
                                                  'date': 'Thu, 18 Jun 2020 15:54:47 GMT', 
                                                  'server': 'AmazonEC2'}, 
                                                  'RetryAttempts': 0}}

我试图从这个失败中提取值“tgw-rtb-0461b603f87a09881”。 尝试过使用

print (response['TransitGatewayRouteTables']['TransitGatewayRouteTableId'])

但这给出了一个错误:“列表索引必须是整数或切片,而不是 str:TypeError”

我可以通过以下方式更深入地了解:

rtid = response.values()
print(rtid)

这让我了解以下内容

dict_values([[{'TransitGatewayRouteTableId': 'tgw-rtb-0461b603f87a09881', 'TransitGatewayId': 'tgw-0d79045d0f874bfd4', 'State': 'available', 'DefaultAssociationRouteTable': False, 'DefaultPropagationRouteTable': True, 'CreationTime': datetime.datetime(2020, 6, 18, 2, 32, 25, tzinfo=tzlocal()), 'Tags': []}], {'RequestId': '6a0ec6df-c41c-4e06-b98d-1afff74e5915', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '6a0ec6df-c41c-4e06-b98d-1afff74e5915', 'content-type': 'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'vary': 'accept-encoding', 'date': 'Thu, 18 Jun 2020 16:13:00 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}])

不太确定我是否朝着正确的方向前进。 如果有人可以帮助描述如何提取所需的值,那就太好了。

在嵌套字典的情况下,您必须使用索引[0]来访问外部字典的值,这是一个列表,然后是从内部字典中获取值的键

print (response['TransitGatewayRouteTables'][0]['TransitGatewayRouteTableId'])
# tgw-rtb-0461b603f87a09881

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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