0

I have an existing DynamoDB table, and I want to write some Python code to append an attribute (of type List) to the table. Here is what I tried:

users.put_item(

    Item={

        "new_attribute": []

    }

)

But this didn't work. I looked everywhere online but couldn't find anything, I know I must be missing something basic. Any help?

2 Answers 2

2

Here is a full example which works

    ### Simulating an Insert and Update to a List

    #Create Table
    import boto3
    dynamodb = boto3.resource('dynamodb')
    try:
        table = dynamodb.create_table(
                TableName='Test_list',
                KeySchema=[
                    {
                        'AttributeName': '_id',
                        'KeyType': 'HASH'  # Partition key
                    }
                ],
                AttributeDefinitions=[
                    {
                        'AttributeName': '_id',
                        'AttributeType': 'N'
                    }
                ],
                ProvisionedThroughput={
                    'ReadCapacityUnits': 5,
                    'WriteCapacityUnits': 5
                }
            )

    except ClientError as e:
        if e.response['Error']['Code']:
            print(e.response['Error']['Message'])
        print( e.response)

    ## Add a record with a list
    table= dynamodb.Table('Test_list')
    ll=['one','two']
    resp=table.put_item(
    Item={
        '_id': 1,
        'mylist': ll
    }
    )

    #Update the list
    new_ll=['three','four']
    response = table.update_item(
        Key={
            '_id': 1
        },
        UpdateExpression="SET #l = list_append(#l, :vals)",
        ExpressionAttributeNames={
            "#l":  'mylist'
        },
        ExpressionAttributeValues={
            ":vals":  new_ll
        }
    )

    # fetch the record to verify
    resp=table.get_item(Key={'_id':1})
    resp['Item']


You will see the output :

{'_id': Decimal('1'), 'mylist': ['one', 'two', 'three', 'four']}
Sign up to request clarification or add additional context in comments.

Comments

0
import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('<your-ddb-table-name>')

table.update_item(
    Key={
        'PK': '<pk>',
        'SK': '<sk>'
    },
    UpdateExpression='SET new_attribute = :list',
    ExpressionAttributeValues={
        ':list': []
    }
)

1 Comment

I pasted the code into an otherwise blank file but am getting this error message: botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: The provided key element does not match the schema

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.