How to add to a 'Map of Maps' in DynamoDB with boto3 (python)

Viewed 1377

I have the following structure in DynamoDB:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    }
  },
  "username": "my-username"
}

How do I add a '3rd fruit item' with its associated attributes? I am aiming to achieve the following:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    },
    "3": {
      "identifier": "pear",
      "colour": "green"
    }
  },
  "username": "my-username"
}

I have tried something similar to the following:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3.identifier = :i, fruits.3.colour = :c',
    ExpressionAttributeValues={
        ':i': 'pear',
        ':c': 'green'
    }
)

Thank you!

1 Answers

You cannot directly set attributes such as fruits.3.identifier because fruits.3 does not exist yet. Instead, you must set fruits.3 as a whole object.

Your update expression should be something like this:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3 = :newFruit',
    ExpressionAttributeValues={
        ':newFruit': {
            'colour': 'green',
            'identifier': 'pear'
        }
    }
)
Related