DynamoDB PutItem in Python (boto3)
put_item writes a whole item, creating it or replacing any existing item with the same primary key. The boto3 resource API takes native Python types — pass plain strings and Decimal numbers, no type descriptors.
Code
import boto3
from decimal import Decimal
from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.Table("Music")
def add_song():
try:
table.put_item(
Item={
"Artist": "Arturo Sandoval",
"SongTitle": "Cubano Chant",
"AlbumTitle": "Danzon",
"Year": Decimal("1994"),
"Awards": Decimal("0"),
},
# Only write if no item with this key already exists
ConditionExpression="attribute_not_exists(Artist) AND attribute_not_exists(SongTitle)",
)
print("Song written")
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
print("A song with that key already exists — not overwritten")
else:
raise
if __name__ == "__main__":
add_song()Explanation
Item— must contain the full primary key, plus any other attributes.- Use
Decimalfor numbers — boto3 rejects Pythonfloat(it can't represent them exactly). Wrap numeric values inDecimal("...")(from a string, to keep precision). - Put replaces — without a condition,
put_itemsilently overwrites an existing item with the same key. Useupdate_itemto change a few attributes without clobbering the rest. ConditionExpression—attribute_not_exists(<key>)makes this a create-only insert; the write raisesClientErrorwith codeConditionalCheckFailedExceptionif the item already exists.- Add
ReturnValues="ALL_OLD"to get the overwritten item back.
Do it visually
Writing a conditional put by hand? The DynamoDB Expression Builder assembles the ConditionExpression and copies the code.
To add and edit items in a GUI — a form per attribute, type pickers, copy-as-boto3 — download DynoTable.
Related guides
- DynamoDB condition expressions —
attribute_not_exists, optimistic locking, and more. - DynamoDB data types — why numbers must be
Decimal.