Python DynamoDB: How to Insert Data

Last updated 1 month ago | 93 views 75     5

Tags:- Python DynamoDB

In this article, you'll learn how to insert items into a DynamoDB table using Python and Boto3, the AWS SDK for Python. We'll cover the fundamentals, syntax, complete examples, and also touch on best practices and common mistakes.


Table of Contents

  1. Introduction to DynamoDB Insert (PutItem)

  2. Prerequisites

  3. Install Boto3 and Set Up Credentials

  4. Insert Single Item into DynamoDB Table

  5. Insert Multiple Items (Batch Write)

  6. Full Working Example

  7. Tips and Best Practices

  8. Common Pitfalls

  9. Conclusion


1. Introduction to DynamoDB Insert (PutItem)

In DynamoDB, inserting data is done via the PutItem operation.

  • Each item is a row in a table.

  • Each item must contain the partition key (and sort key if applicable).

  • DynamoDB is schema-less, so you can store different attributes in different items, as long as the key structure is consistent.


⚙️ 2. Prerequisites

Make sure you have the following:

  • AWS account with DynamoDB permissions

  • Python 3.7+

  • An existing DynamoDB table (e.g., Users)

  • AWS CLI or credentials configured locally


3. Install Boto3 and Set Up AWS Credentials

Install Boto3

pip install boto3

Configure AWS Credentials

Use the AWS CLI to configure your credentials:

aws configure

✍️ 4. Insert Single Item into DynamoDB Table

Here’s how to insert a single item into the Users table.

import boto3

# Connect to DynamoDB
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')

# Reference the table
table = dynamodb.Table('Users')

# Insert a single item
response = table.put_item(
    Item={
        'user_id': '001',  # Partition key (required)
        'name': 'Alice Smith',
        'email': '[email protected]',
        'age': 30
    }
)

print("Insert response:", response)

Explanation:

  • Item: Dictionary of attributes.

  • The user_id is required because it’s the partition key defined when the table was created.


5. Insert Multiple Items (Batch Write)

DynamoDB supports batch inserts via batch_writer.

with table.batch_writer() as batch:
    batch.put_item(Item={'user_id': '002', 'name': 'Bob', 'email': '[email protected]'})
    batch.put_item(Item={'user_id': '003', 'name': 'Charlie', 'email': '[email protected]'})
    batch.put_item(Item={'user_id': '004', 'name': 'Daisy', 'email': '[email protected]'})

batch_writer() automatically handles retries and chunking up to 25 items per batch.


✅ 6. Full Working Example

import boto3

# Connect to DynamoDB
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
table = dynamodb.Table('Users')

# Insert single item
table.put_item(
    Item={
        'user_id': '005',
        'name': 'Eve Summers',
        'email': '[email protected]',
        'age': 25
    }
)

# Insert multiple items using batch_writer
with table.batch_writer() as batch:
    batch.put_item(Item={'user_id': '006', 'name': 'Frank', 'email': '[email protected]'})
    batch.put_item(Item={'user_id': '007', 'name': 'Grace', 'email': '[email protected]'})

print("Data inserted successfully.")

7. Tips and Best Practices

Tip Description
✅ Use batch_writer() for bulk inserts More efficient and reliable
✅ Include only relevant attributes DynamoDB is schema-less, avoid unnecessary fields
✅ Validate key fields before insert Always include partition key (and sort key if needed)
Never store credentials in code Use IAM roles, profiles, or environment variables
Monitor usage Use CloudWatch for capacity, throttling, and errors

⚠️ 8. Common Pitfalls

Pitfall Solution
❌ Missing partition key Always include user_id or other defined key
❌ Exceeding batch size Max 25 items per batch_writer() call
❌ Using wrong attribute types Must match types defined in AttributeDefinitions (e.g., S, N)
❌ Overwriting items unintentionally PutItem replaces items with the same key
❌ Ignoring retry logic Use batch_writer() to handle retries automatically

9. Conclusion

Inserting data into a DynamoDB table using Python is easy with Boto3. You can insert one item at a time or use batch operations for efficiency.

In this tutorial, you learned:

  • How to insert a single item using put_item()

  • How to insert multiple items using batch_writer()

  • How to avoid common mistakes and write robust DynamoDB insert logic


Next Steps:

  • Learn how to query and filter data in DynamoDB using get_item() and query()

  • Explore update and delete operations

  • Implement error handling and retry logic