Python DynamoDB: Update Items Using Boto3

Last updated 1 month, 4 weeks ago | 133 views 75     5

Tags:- Python DynamoDB

Updating data in DynamoDB is a powerful operation that allows you to modify existing records based on their primary key (partition key + sort key, if any). With Python and Boto3, you can update attributes, increment values, or conditionally perform updates.


Table of Contents

  1. Introduction to Updates in DynamoDB

  2. Prerequisites

  3. Basic Update Syntax

  4. Update Multiple Attributes

  5. Use Expression Attribute Names & Values

  6. Conditional Updates

  7. Incrementing Numeric Values

  8. Complete Code Example

  9. Tips and Best Practices

  10. Common Pitfalls

  11. Conclusion


1. Introduction to Updates in DynamoDB

DynamoDB’s update_item() operation allows you to modify one or more attributes of an existing item. You must know the primary key (partition key and sort key, if applicable).

Update features:

  • Modify existing attributes

  • Add new attributes

  • Perform conditional updates

  • Atomically increment numbers

  • Return updated values


⚙️ 2. Prerequisites

Before you begin, ensure:

  • Python 3.7+

  • boto3 installed (pip install boto3)

  • AWS credentials are set (aws configure)

  • A DynamoDB table is created (e.g., Users)

Table schema example:

  • Partition key: user_id (string)

  • Optional sort key: email (string)


3. Basic Update Syntax

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')

response = table.update_item(
    Key={'user_id': '001'},
    UpdateExpression='SET age = :val1',
    ExpressionAttributeValues={':val1': 30},
    ReturnValues='UPDATED_NEW'
)

print("Updated attributes:", response['Attributes'])

4. Update Multiple Attributes

You can update multiple fields at once:

response = table.update_item(
    Key={'user_id': '001'},
    UpdateExpression='SET age = :a, city = :c',
    ExpressionAttributeValues={
        ':a': 31,
        ':c': 'Los Angeles'
    },
    ReturnValues='UPDATED_NEW'
)

5. Using Expression Attribute Names

If an attribute name is a reserved word (like name), use ExpressionAttributeNames.

response = table.update_item(
    Key={'user_id': '001'},
    UpdateExpression='SET #nm = :n',
    ExpressionAttributeNames={'#nm': 'name'},
    ExpressionAttributeValues={':n': 'John Doe'},
    ReturnValues='UPDATED_NEW'
)

✅ 6. Conditional Updates

Ensure that an update only happens if a condition is met.

from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError

try:
    response = table.update_item(
        Key={'user_id': '001'},
        UpdateExpression='SET age = :new_age',
        ExpressionAttributeValues={':new_age': 35},
        ConditionExpression=Attr('status').eq('active'),
        ReturnValues='UPDATED_NEW'
    )
    print("Update succeeded:", response['Attributes'])
except ClientError as e:
    if e.response['Error']['Code'] == "ConditionalCheckFailedException":
        print("Condition not met. Update aborted.")
    else:
        raise

➕ 7. Incrementing Numeric Values Atomically

DynamoDB supports atomic increments with SET attr = attr + :val.

response = table.update_item(
    Key={'user_id': '001'},
    UpdateExpression='SET login_count = if_not_exists(login_count, :zero) + :inc',
    ExpressionAttributeValues={
        ':inc': 1,
        ':zero': 0
    },
    ReturnValues='UPDATED_NEW'
)

This pattern ensures the attribute is initialized if it doesn’t exist.


8. Complete Code Example

import boto3
from boto3.dynamodb.conditions import Attr
from botocore.exceptions import ClientError

def update_user(user_id, new_age, city):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Users')

    try:
        response = table.update_item(
            Key={'user_id': user_id},
            UpdateExpression='SET age = :a, city = :c',
            ExpressionAttributeValues={
                ':a': new_age,
                ':c': city
            },
            ConditionExpression=Attr('status').eq('active'),
            ReturnValues='UPDATED_NEW'
        )
        print("User updated successfully:", response['Attributes'])
    except ClientError as e:
        if e.response['Error']['Code'] == "ConditionalCheckFailedException":
            print(f"User {user_id} not updated — condition not met.")
        else:
            raise

# Example usage
update_user('001', 32, 'San Francisco')

9. Tips and Best Practices

Tip Reason
✅ Use ReturnValues='UPDATED_NEW' Returns the updated fields only
✅ Use if_not_exists() Safely increment undefined attributes
✅ Use ExpressionAttributeNames Avoid issues with reserved words
✅ Use ConditionExpression Prevent accidental updates
✅ Handle exceptions Prevent app crashes on failed updates

⚠️ 10. Common Pitfalls

Pitfall Solution
❌ Missing a required key Always provide full primary key (partition + sort key if applicable)
❌ Updating reserved attribute names Use ExpressionAttributeNames
❌ Forgetting return values Use ReturnValues='UPDATED_NEW' to see the result
❌ Overwriting by mistake Use conditions to guard updates
❌ Assuming update creates a new item It only updates if the key exists (unless condition prevents it)

✅ 11. Conclusion

DynamoDB updates using Python and Boto3 are highly flexible. With update_item() you can:

  • Modify single or multiple fields

  • Perform atomic operations

  • Add conditional logic

  • Handle partial updates efficiently

By understanding expressions, return values, and conditions, you can safely manage and manipulate your data in DynamoDB.