Home > Blockchain >  Get values from Python dictionaries
Get values from Python dictionaries

Time:10-19

I have a function that returns the following dictionary:

{
  "Attributes": {
    "ApproximateNumberOfMessages": "0"
  },
  "ResponseMetadata": {
    "RequestId": "feed6129-46ce-5af2-b0f7-38c1e632ae2c",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "feed6129-46ce-5af2-b0f7-38c1e632ae2c",
      "date": "Tue, 19 Oct 2021 10:32:28 GMT",
      "content-type": "text/xml",
      "content-length": "357"
    },
    "RetryAttempts": 0
  }
}

>>> type(result)
<class 'dict'>

>>> result.keys()
dict_keys(['Attributes', 'ResponseMetadata'])

How can i get the values of "ApproximateNumberOfMessages" as an integer?

CodePudding user response:

The following will do:

messages = int(result["Attributes"]["ApproximateNumberOfMessages"])

CodePudding user response:

As has been noted, if you know the full path will always exist you can do

messages = int(result["Attributes"]["ApproximateNumberOfMessages"])

If you are uncertain whether either Attributes or ApproximateNumberOfMessages will exist you will need to be a bit more careful.

messages = 0
attributes = result.get("Attributes")
if attributes:
   messages = int(attributes.get("ApproximateNumberOfMessages", 0))

Accessing eg. result["Attributes"] when it doesn't exist will throw an error otherwise. get allows you to specify a default if need be.

  • Related