Skip to content

Instantly share code, notes, and snippets.

@pictolearn
Last active February 11, 2023 12:34
Show Gist options
  • Save pictolearn/dcf5e0bec3f324fe951cbc9eab275b9b to your computer and use it in GitHub Desktop.
Save pictolearn/dcf5e0bec3f324fe951cbc9eab275b9b to your computer and use it in GitHub Desktop.
update an item in a DynamoDB table by running a python script
# update an item in the table
# boto3, an AWS SDK package
# JSON, a text format package that is language independent
# decimal, a precision Handling package
import boto3
import json
import decimal
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
# service resource request and region are set
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('<table name>')
title = "The Big New Movie"
year = 2015
# updation of items occur
response = table.update_item(
Key={
'year': year,
'title': title
},
UpdateExpression="set info.rating = :r, info.plot=:p, info.actors=:a",
ExpressionAttributeValues={
# decimal, Converts a finite Decimal instance to a rational number, exactly.
':r': decimal.Decimal(5.5),
':p': "Everything happens all at once.",
':a': ["Larry", "Moe", "Curly"]
},
ReturnValues="UPDATED_NEW"
)
print("UpdateItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))
@giribabu22
Copy link

How it will work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment