Home > Back-end >  How can I itterate over nested dictionaries and lists in boto3 to obtain particular values?
How can I itterate over nested dictionaries and lists in boto3 to obtain particular values?

Time:12-12

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?

CodePudding user response:

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)
  • Related