Home > OS >  How to itterate over a nested list that's inside a dictionary?
How to itterate over a nested list that's inside a dictionary?

Time:09-23

I'm trying to itterate over the 'Resource' key to determine if it satisfies a condition.

I have a use case where I have to itterate over each of the resource keys to determine if it's equal to a particular value. Essentially, I am just validating the policy has the correct permissions.

{'Action': ['s3:PutObject', 'kms:GenerateKey'],
'Effect': 'Allow'
'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*',
'arn:aws:s3:::bucket]}

Is there a way I can iterate over each value in the list for Resource?

So far I have this

for value in policy:
    Resource = value['Resource']
    for resource in Resources:
        if resource == 'arn:aws:s3:::bucket'
        return True

However, I just realized this does not work as expected.

CodePudding user response:

You can simply get the array corresponding to 'Response' key in dictionary and iterate over it.

dct = {'Action': ['s3:PutObject', 'kms:GenerateKey'],
'Effect': 'Allow'
'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*',
'arn:aws:s3:::bucket']}

resource = dct.get('Resource')
for array_element in resource:
    # do stuff as you wish with each array_element

CodePudding user response:

I have a feeling you actually want to do this:

bucket_policies = [
    each for each in policy 
    if 'arn:aws:s3:::bucket' in each['Resource']
]

This will get you a list of the policies in policy that has that key in resource.

CodePudding user response:

Are you wanting this:

dct ={'Action': ['s3:PutObject', 'kms:GenerateKey'],'Effect':'Allow',
   'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*','arn:aws:s3:::bucket']}

for r in dct.get('Resource'):
    print(r)

Output:

arn:aws:kms:us-west-2:<account_id>:key/*
arn:aws:s3:::bucket

You can use in and dct.get('Resource') like below:

>>> print('arn:aws:s3:::bucket' in dct.get('Resource'))
True
>>> print('arn:aws:kms:us-west-2:<account_id>:key/*' in dct.get('Resource'))
True
>>> print('lara lara ' in  dct.get('Resource'))
False
  • Related