You need to enable JavaScript to run this app. 如何使用boto3的client.put_item方法向DynamoDB写入字典列表
优惠活动
大模型
产品
解决方案
定价
更多

如何使用boto3的client.put_item方法向DynamoDB写入字典列表

问题根因

你当前写法无法正常写入cart字段的核心原因是:boto3 提供的低层级 DynamoDB Client 不会自动完成 Python 原生数据类型到 DynamoDB 专属属性格式的转换。
你传入的{"L": cart}中,cart是未经过格式转换的 Python 原生字典列表,列表里的每个元素、每个元素包含的字段都不符合 DynamoDB 的属性值格式要求,因此写入会失败。

正确格式化逻辑

DynamoDB 的列表类型(L)要求数组内的每一个元素,都必须是合法的 DynamoDB 属性值,对应转换规则为:

  • Python 原生字典对应 DynamoDB 的映射类型(M)
  • 字符串字段对应 DynamoDB 的字符串类型(S)
  • 数值字段对应 DynamoDB 的数值类型(N),且数值必须转为字符串形式传入

以你给出的长度可变购物车列表为例,完成格式转换后的合法cart字段值为:

{
  "L": [
    {"M": {"name": {"S": "chicken"}, "price": {"N": "6.23"}}},
    {"M": {"name": {"S": "beef"}, "price": {"N": "5.34"}}},
    {"M": {"name": {"S": "pork"}, "price": {"N": "8.48"}}}
  ]
}

因为列表长度可变,只需要遍历每个购物车条目追加到转换后的数组里即可,不需要写死固定长度。

修正后的底层Client实现代码
def create_order(order_id, cart, total):
    dynamodb = boto3.client('dynamodb')
    table = 'Orders'
    # 遍历原始购物车列表,逐条目做格式适配
    formatted_cart = []
    for goods in cart:
        formatted_cart.append({
            "M": {
                "name": {"S": goods["name"]},
                # N类型要求入参为字符串格式的数值
                "price": {"N": str(goods["price"])}
            }
        })
    
    response = dynamodb.put_item(
        TableName=table,
        Item={
            'order_id': {"S": order_id},
            'order_total': {"N": str(total)},
            'cart': {"L": formatted_cart}
        }
    )
    return response
简化实现方案(无需手动格式化)

如果不想手动逐字段做类型映射,可以切换为 boto3 的高层级 Resource 接口,该接口会自动完成 Python 原生类型到 DynamoDB 格式的转换,对应代码写法:

def create_order(order_id, cart, total):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Orders')
    # 直接传入原生Python类型即可,接口自动完成格式转换
    response = table.put_item(
        Item={
            'order_id': order_id,
            'order_total': total,
            'cart': cart
        }
    )
    return response

内容的提问来源于stack exchange,提问作者John Zheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 00:06:03