简体   繁体   中英

How can I itterate over nested dictionaries and lists in boto3 to obtain particular values?

I'm trying to itterate over these values to retrive the Tags to see if any of the tag values match "AWSNetworkFirewallManaged" .

I'm having problems figuring out a solution to achieve this.

response = {
    "VpcEndpoints": [
        {
            "VpcEndpointId": "vpce-123",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-test",
            "ServiceName": "com.amazonaws.com",
            "State": "available",
            "SubnetIds": [
                "subnet-random"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-123"
            ],
            "CreationTimestamp": "2022-10-28T01:23:23.924Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "true"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:us-west-2"
                }
            ],
            "OwnerId": "123"
        },
        {
            "VpcEndpointId": "vpce-123",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-<value>",
            "ServiceName": "com.amazonaws.vpce.us-west-2",
            "State": "available",
            "SubnetIds": [
                "subnet-<number>"
            ],
            "IpAddressType": "ipv4",
            "RequesterManaged": True,
            "NetworkInterfaceIds": [
                "eni-<value>"
            ],
            "CreationTimestamp": "2022-10-28T01:23:42.113Z",
            "Tags": [
                {
                    "Key": "AWSNetworkFirewallManaged",
                    "Value": "True"
                },
                {
                    "Key": "Firewall",
                    "Value": "arn:aws:network-firewall:%l"
                }
            ],
            "OwnerId": "random"
            }
        ]
    }

So far I have

for endpoint in DESCRIBE_VPC_ENDPOINTS['VpcEndpoints']:
    print(endpoint['VpcEndpointId']['Tags']

However this needs to be indice, but if it is I do not know if it will still itterate over the rest of the VPC endpoint ids.

Any suggestions or guidence on this?

You can use double for loop:

for endpoint in response['VpcEndpoints']:
  for tags in endpoint['Tags']:
    if 'AWSNetworkFirewallManaged' in tags.values():
     print(endpoint['VpcEndpointId'], tags)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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