sim
sim

Reputation: 488

How to delete items from dynamodb list

import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('myowntable')
response = []
response_table = table.get_item(Key={'id': '19'})
        if 'Item' in response_table and response_table['Item']:
            response.append(response_table['Item'])

listofvalues = [1,2,3]
for i in listofvalues:
    id_index_delete = str(response[0]['myList'].index(i))
    query = "REMOVE myList[" + id_index_delete + "]"
    table.update_item(
                    Key={
                        'id': '19'
                    },
                    UpdateExpression=query
                )

Upvotes: 0

Views: 3910

Answers (2)

fedonev
fedonev

Reputation: 25669

You can remove multiple items from a list in a signle operation with an update expression like REMOVE myList[0], myList[2]. Here's one way to do it using boto3:

id = 'a1'
response_table = table.get_item(Key={'id': id})
response = response_table.get('Item', {}).get('myList', [])
listofvalues = [1,2,3] # remove these items from myList

items_to_remove = [f'myList[{response.index(x)}]' for x in listofvalues if x in response ]
query = "REMOVE " +  ", ".join(items_to_remove)

if len(items_to_remove):
  table.update_item(Key={'id': id}, UpdateExpression=query)

Upvotes: 2

Ross Williams
Ross Williams

Reputation: 632

If you turn your list into a map, you can then delete items based on the map key and do all deletes in one operation.

Old: [1,2,3]

New: {“1”:1,”2”:2,”3”:3}

Upvotes: 0

Related Questions