Python DynamoDB: How to Create a Table (Database Equivalent)

Last updated 1 month ago | 99 views 75     5

Tags:- Python DynamoDB

In Amazon DynamoDB, there is no separate database creation step like in traditional relational databases. Instead, each table is a self-contained database. To get started with storing data in DynamoDB using Python, your first task is to create a table.

This guide walks you through creating a DynamoDB table using Python, explains the key concepts, and provides a complete working code example.


Table of Contents

  1. Understanding DynamoDB Table Structure

  2. Prerequisites

  3. Install Boto3 (AWS SDK for Python)

  4. Configure AWS Credentials

  5. Creating a DynamoDB Table with Python

  6. Full Working Example

  7. Tips and Best Practices

  8. Common Pitfalls

  9. Conclusion


1. Understanding DynamoDB Table Structure

In DynamoDB:

  • A table is the top-level data container (analogous to a database in SQL).

  • Each table has:

    • Partition Key (mandatory)

    • Sort Key (optional)

    • Provisioned or On-Demand Throughput

  • Tables are schema-less beyond the key definitions, meaning items can have different attributes.


⚙️ 2. Prerequisites

  • An AWS account

  • Python 3.7+

  • IAM user with permissions for DynamoDB

  • AWS credentials configured locally


3. Install Boto3

Boto3 is the AWS SDK for Python.

pip install boto3

4. Configure AWS Credentials

Use the AWS CLI to configure:

aws configure

You'll be prompted to enter:

  • AWS Access Key ID

  • AWS Secret Access Key

  • Default Region (e.g., us-east-1)

  • Output format (json is recommended)


5. Creating a DynamoDB Table with Python

Here's how to create a simple table named Users with a user_id as the partition key:

➤ Code to Create a Table

import boto3

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

# Create a new table
table = dynamodb.create_table(
    TableName='Users',
    KeySchema=[
        {
            'AttributeName': 'user_id',
            'KeyType': 'HASH'  # Partition key
        }
    ],
    AttributeDefinitions=[
        {
            'AttributeName': 'user_id',
            'AttributeType': 'S'  # S = String
        }
    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    }
)

# Wait until the table exists
table.meta.client.get_waiter('table_exists').wait(TableName='Users')
print("Table created. Status:", table.table_status)

✅ 6. Full Working Example

Here’s a complete working script:

import boto3
import os

# Optional: Set AWS credentials programmatically (not recommended for production)
# os.environ['AWS_ACCESS_KEY_ID'] = 'your-access-key-id'
# os.environ['AWS_SECRET_ACCESS_KEY'] = 'your-secret-access-key'
# os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'

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

# Table name
table_name = 'Users'

# Check if table exists
existing_tables = [table.name for table in dynamodb.tables.all()]
if table_name not in existing_tables:
    table = dynamodb.create_table(
        TableName=table_name,
        KeySchema=[{'AttributeName': 'user_id', 'KeyType': 'HASH'}],
        AttributeDefinitions=[{'AttributeName': 'user_id', 'AttributeType': 'S'}],
        ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
    )

    # Wait until table is ready
    table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
    print(f"Table '{table_name}' created successfully!")
else:
    print(f"Table '{table_name}' already exists.")

7. Tips and Best Practices

Tip Why It Matters
Use ProvisionedThroughput carefully Helps control costs and ensure availability
Use On-Demand billing for unpredictable workloads More scalable and cost-effective for sporadic access
Always use a meaningful partition key Crucial for performance and even data distribution
Consider adding a sort key Enables complex queries and range scans
Wait for table readiness Use waiter to ensure the table is available before accessing it

⚠️ 8. Common Pitfalls

Pitfall Solution
❌ Forgetting to wait for table creation Always use table_exists waiter
❌ Using wrong attribute types Use only S (String), N (Number), or B (Binary)
❌ Creating too many tables unnecessarily DynamoDB is optimized for fewer, larger tables
❌ Hardcoding credentials Use IAM roles, environment variables, or AWS config instead
❌ Skipping key schema You must specify at least the partition key

9. Conclusion

In DynamoDB, creating a table is the equivalent of creating a database. Using Python and Boto3, you can programmatically manage your data models and scale them as needed.

✅ You’ve learned:

  • How to connect to DynamoDB using Python

  • How to define a table’s key schema and attribute types

  • How to handle table creation and readiness properly

  • What best practices and common mistakes to watch for