如何添加到';地图地图';在DynamoDB中使用boto3(python)

如何添加到';地图地图';在DynamoDB中使用boto3(python),python,amazon-web-services,amazon-dynamodb,boto3,Python,Amazon Web Services,Amazon Dynamodb,Boto3,我在DynamoDB中有以下结构: { "fruits": { "1": { "identifier": "orange", "colour": "orange" }, "2": { "identifier": "strawberry", "colour": "red" } }, "username": "my-username" } 如何添加“第三个水果项目”及其相关属性?我的目标是实现以下目标: {

我在DynamoDB中有以下结构:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    }
  },
  "username": "my-username"
}
如何添加“第三个水果项目”及其相关属性?我的目标是实现以下目标:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    },
    "3": {
      "identifier": "pear",
      "colour": "green"
    }
  },
  "username": "my-username"
}
result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3.identifier = :i, fruits.3.colour = :c',
    ExpressionAttributeValues={
        ':i': 'pear',
        ':c': 'green'
    }
)
我尝试过类似于以下的方法:

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

谢谢大家!

您不能直接设置属性,例如
水果.3.标识符
,因为
水果.3
尚不存在。相反,您必须将
fruits.3
设置为一个整体对象

您的更新表达式应该如下所示:

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