Andrew Allison
Andrew Allison

Reputation: 1146

Boto3 list_append a value to overwrite a null value in a list

I am writing a small lambda function to update a game item in my DynamoDB. My game item has a participants attribute which is a list consisting of the participant_id of each participant in the game. When a game doesn't have any participants yet (i.e. a round later in the bracket) the list will hold 2 null values:

Empty participant list

I would like to overwrite the null values with a string each time I add a new participant. Currently I am able to append a new String to the list but the null values remain:

After adding a participant

How can I overwrite one of the 2 null values with a string using boto3? (i.e. to where it looks like ["participantOneId", Null] after adding one participant and ["participantOneId", "participantTwoId"] after adding both participants) This is my current implementation:

import boto3
import json

dynamodb = boto3.resource("dynamodb")
gamesTable = dynamodb.Table('games')

def lambda_handler(event, context):
  # get "next_game_id" and "winner_id" from the event body
  updated_next_game = gamesTable.update_item(
      Key={'id': next_game_id },
      UpdateExpression="SET participants = list_append(participants, :i)",
      ExpressionAttributeValues={
        ':i': [winner_id],
      },
      ReturnValues="ALL_NEW"
  )

Upvotes: 0

Views: 973

Answers (1)

B. Shefter
B. Shefter

Reputation: 897

If you don't need to append anything to the list, then you don't want to use list_append. Something like this should work fine:

UpdateExpression="SET participants[0] = <whatever>"

and/or

UpdateExpression="SET participants[1] = <whatever>"

(If you won't know in advance which of the two elements you need to set, you can always use if_not_exists.)

Upvotes: 1

Related Questions