DynamoDB UpdateItem in Python (boto3)
update_item changes specific attributes of one item (and creates it if absent), leaving everything else untouched. With the boto3 resource API you pass an UpdateExpression plus native values (Decimal for numbers).
Code
import boto3
from decimal import Decimal
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("Music")
def update_song():
response = table.update_item(
Key={
"Artist": "Arturo Sandoval",
"SongTitle": "Cubano Chant",
},
UpdateExpression="SET Genre = :genre, #yr = :year ADD Awards :inc",
ExpressionAttributeNames={"#yr": "Year"},
ExpressionAttributeValues={
":genre": "Latin Jazz",
":year": Decimal("1994"),
":inc": Decimal("1"),
},
ReturnValues="ALL_NEW",
)
print(response["Attributes"]) # the item after the update
return response["Attributes"]
if __name__ == "__main__":
update_song()Explanation
Key— the full primary key of the item to update.UpdateExpression— one or more clauses:SETassigns attributes (Genre = :genre).Yearis reserved, so it's aliased to#yr.ADDon a number is an atomic increment (ADD Awards :inc) — no read-modify-write race.REMOVEdeletes an attribute;DELETEremoves elements from a set.
ExpressionAttributeValues— the:placeholder→ value map. Numbers must beDecimal, notfloat.ReturnValues—"ALL_NEW"returns the full item after the update (alsoUPDATED_NEW,ALL_OLD,UPDATED_OLD,NONE).- Upsert semantics —
update_itemcreates the item if the key doesn't exist. Add aConditionExpression(e.g.attribute_exists(Artist)) to update-only.
Do it visually
The DynamoDB Expression Builder builds SET / ADD / REMOVE clauses with the name/value maps and copies runnable code.
To edit items in a GUI — change a field, review the generated UpdateExpression, copy the boto3 code — download DynoTable.
Related guides
- DynamoDB update expressions —
SET,ADD,REMOVE,DELETE, and idioms. - Understanding ReturnValues — what each
ReturnValuesoption gives you.