Skip to content

Delete Items in DynamoDB using Python

Posted on:August 5, 2023 at 05:17 AM

In this blog, we will learn how to delete items in DynamoDB using Python and boto3. We can only delete one item at a time in DynamoDB.

Table of contents

Open Table of contents

Delete Item in DynamoDB

When we want to delete an item in the DynamoDB table, we must pass the item’s full primary key in the function call.

import boto3
from pprint import pprint

boto3.setup_default_session(profile_name="ah")

table_name = "orders"
dynamodb_resource = boto3.resource("dynamodb")
orders_table = dynamodb_resource.Table(table_name)


def delete_item():
    response = orders_table.delete_item(
        Key={
            "order_id": "ord100",
            "order_date": "2022-07-01",
        }
    )

    pprint(response)

The above code deletes an item in the DynamoDB table with an order_id of ‘ord100’ and order_date of ‘2022-07-01’.

Deleting DynamoDB Item with Condition

We can also use DynamoDB delete API to delete an item only when some condition is true. For example, we want to delete an order only if it has an item count of 0. We can achieve that using the below code.

def delete_item_with_condition():
    response = orders_table.delete_item(
        Key={
            "order_id": "ord100",
            "order_date": "2022-07-01",
        },
        ConditionExpression="item_count = :v",
        ExpressionAttributeValues={
            ":v": 0,
        },
    )
    pprint(response)

The above code will only delete this item if the item_count for this order is 0. If item_count is not 0, then the code throws the following exception.

botocore.errorfactory.ConditionalCheckFailedException: An error occurred
(ConditionalCheckFailedException) when calling the DeleteItem operation: \
The conditional request failed

Delete Multiple Items in the DynamoDB Table using Python

DynamoDB delete API does not support deleting multiple items in a single call. However, we can use BatchDelete API to delete multiple items in the DynamoDB table. I will soon be publishing a blog about it, so stay tuned. See you in the next blog.