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 Decimal for numbers — boto3 rejects Python float (it can't represent them exactly). Wrap numeric values in Decimal("...") (from a string, to keep precision).
  • Put replaces — without a condition, put_item silently overwrites an existing item with the same key. Use update_item to change a few attributes without clobbering the rest.
  • ConditionExpressionattribute_not_exists(<key>) makes this a create-only insert; the write raises ClientError with code ConditionalCheckFailedException if 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.

Mit DynamoDB ohne die Console arbeiten

DynoTable ist ein schneller Desktop-Client für DynamoDB — durchsuche Tabellen, führe SQL-artige Queries aus und bearbeite Items lokal.