-1

I have a simple table where primary key is ID and other attributes are name and balance. Now there are some rows where balance can be NULL. When I am fetching those attributes using Lambda function it cannot handle it. I want to handle these cases so that when a NULL attribute is detected it can show some message.

import json
import boto3
def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("demoTable")
    response = table.get_item(
    Key = {
            'ID': '9898'
    }
    
    )
    item = str(response['Item']['balance'])
    print(item)

1 Answers1

1

Your problem is in:

response['Item']['balance']

Generally, using square brackets to access dictionary members (response is a dictionary) is considered a bad practice. You can use it when you're absolutely sure that the item you're trying to get exists, but a better way is to use get() since it can handle situations where the item does not exist.

response.get('Item', dictionary()).get('balance', 0)

In case the item does not exist, or balance is null, you'll get a 0 as a result

Caldazar
  • 2,801
  • 13
  • 21