2

I have a nested dictionary that I am trying to parse and do not seem to know how to access the third level items. Help is appreciated Here is my dictionary

{
    "FunctionName": "RDSInstanctStart",
    "LastModified": "2018-03-24T07:19:56.792+0000",
    "MemorySize": 128,
    "Environment": {
        "Variables": {
            "DBInstanceName": "test1234"
        }
    },
    "Version": "$LATEST",
    "Role": "arn:aws:iam::xxxxxxx:role/lambda-start-RDS",
    "Timeout": 3,
    "Runtime": "python2.7",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "tBdB+UDA9qlONGb8dgruKc6Gc82gvYLQwdq432Z0118=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "SecurityGroupIds": []
    },
    "CodeSize": 417,
    "FunctionArn": "arn:aws:lambda:us-east-1:xxxxxxxx:function:RDSInstanctStart",
    "Handler": "lambda_function.lambda_handler"
}

I am trying to access the value for the key "Variables" Here is my code so far:

try:           

 for evnt in funcResponse['Environment']['Variables']['DBInstanceName']:
            print (evnt[0])
except ClientError as e:
        print(e)

The result I get is

t
e
s
t
1
2
3
4    

If I do not give the Index of the envt variable, I get a type error.

1
  • 1
    As a side not, you may be interested in something like dpath or one of its competitors to treat the nested collection as a flat collection with complex paths like 'Environment/Variables/DBInstanceName' for keys. Commented Mar 26, 2018 at 20:09

1 Answer 1

4

funcResponse['Environment']['Variables']['DBInstanceName'] is a single string, but you are looping over it. Strings are sequences of single characters.

You'd get the same if you did: for character in "test1234": print(character[0]) (and you can remove the [0] index too, since character is just as string with a single character in it).

Don't loop, just print:

evnt = funcResponse['Environment']['Variables']['DBInstanceName']
print(evnt)

If you wanted to print all environment variables, then you'd have to loop over the items of the funcResponse['Environment']['Variables'] dictionary:

for name, value in funcResponse['Environment']['Variables'].items():
    print(name, value, sep=': ')

In any case, funcResponse['Environment']['Variables'] is just a dictionary. Adding ['DBInstanceName'] to the end gives you the value for the 'DBInstanceName' key.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Martijn. I understand now. Also thanks for the snippet to loop for all environment variables. At some point I will be doing that too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.