Search code examples
amazon-dynamodbboto3

DynamoDB append list to nested list with boto3


I have a DynamoDB object which has a list with lists:

options: [
  ['fish', 'cat', 'dog', 'cow']
]

I want to append another list to it so it looks like this:

options: [
  ['fish', 'cat', 'dog', 'cow'],
  ['bird', 'sheep', 'snake', 'bee']
]

I tried it with the append_list expression SET options = list_append(options, :opt) but the result is a single list merged together of the existing list and the one I am trying to append.


Solution

  • Like this:

    options= [['dog', 'cat']]
    try:
        resp = table.update_item(
            Key={
                'pk': id
            },
            UpdateExpression="SET #options = list_append(if_not_exists(#options, :empty_list), :options)",
            ExpressionAttributeValues={ ":options": options, ":empty_list": []},
            ExpressionAttributeNames={"#options": "options"},
        )
        print(resp['ResponseMetadata'])
    except Exception as e:
        print(e)
    

    You have to append a list, the client will extract the elements from the list, so we nest the parameters within another list.

    I also use if_not_exists as you would get a validation exceptions if you try to append to a list that does not exist already.