[英]How to insert item at index in a DynamoDB list using update_item and Boto3
I have a simple DynamoDB table structure:我有一个简单的 DynamoDB 表结构:
{
id: '123_456',
number_list: ['a', 'c']
}
And I would like to add 'b'
in the middle (or at some specific index) of this array.我想在这个数组的中间(或某个特定索引)添加'b'
。
What I know is that we can use list_append()
to add it at the end such as:我所知道的是,我们可以使用list_append()
在末尾添加它,例如:
table.update_item(
Key={'id': '123_456'},
UpdateExpression="SET number_list = list_append(number_list, :nl)"
ExpressionAttributeValues={ ':nl': ['b'] }
)
This will result in ['a', 'c', 'b']
but I want ['a', 'b', 'c']
.这将导致['a', 'c', 'b']
但我想要['a', 'b', 'c']
。
Is there a way to achieve this or should I get the stored list, add at index in python and store it again with:有没有办法实现这一点,或者我应该得到存储的列表,在 python 的索引处添加并再次存储:
SET list_number = :nln
{ ':nln': ['a', 'b', 'c'] }
I know we can delete at index with REMOVE list_number[1]
which will result in ['a']
.我知道我们可以使用REMOVE list_number[1]
在索引处删除,这将导致['a']
。 I would like to find something similar.我想找到类似的东西。
Many thanks in advance.提前谢谢了。
You can construct new list from older one - if you know exactly where change should happen.您可以从旧列表构建新列表 - 如果您确切知道应该在哪里发生更改。 Here is an example - search for "Appending to a list and updating a specific value at the same time". 这是一个示例 - 搜索“附加到列表并同时更新特定值”。 From that I would try with:从那我会尝试:
UpdateExpression=f"SET #nl[1] = :repl",
ExpressionAttributeNames={
"#nl": "number_list",
},
ExpressionAttributeValues={
":repl": "b"
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.