'How do I append a list to my DynamoDB table using Python?

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?



Solution 1:[1]

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']}

Solution 2:[2]

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': []
    }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sujit Bhattacharyya
Solution 2 jellycsc