Kask
Kask

Reputation: 53

Parse nested Python dict

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.

Upvotes: 2

Views: 261

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

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.

Upvotes: 4

Related Questions