簡體   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