DynamoDB get_item条件判断异常,如何修正得到预期输出?
问题描述
我的代码如下:
def main(): alias = "jen" ddb = boto3.client("dynamodb") get_ddb_item = ddb.get_item(TableName="testtable", Key={"employee": {"S": alias}}) item = get_ddb_item["Item"] print(item) if item == alias: print(f"{alias} is an employee") else: print(f"{alias} is not an active employee")
我的DynamoDB表testtable中仅存在一条数据:主键employee的值为"jen"。预期代码输出“jen is an employee”,但实际运行后得到相反结果“jen is not an active employee”,请问该如何修改代码以得到预期输出?
问题原因与修改方案
问题核心是**boto3.client返回的DynamoDB数据格式是带类型标记的嵌套字典**:
- 调用
get_item后,item的实际结构是{"employee": {"S": "jen"}},不是单纯的字符串"jen"。直接拿这个字典和字符串alias比较,结果必然不相等,所以会进入else分支。
有两种修改方式:
方式1:解析嵌套字典的实际值
提取Item中employee字段对应S类型的字符串值,再和alias比较:
def main(): alias = "jen" ddb = boto3.client("dynamodb") get_ddb_item = ddb.get_item(TableName="testtable", Key={"employee": {"S": alias}}) item = get_ddb_item["Item"] # 提取employee字段的实际字符串值 employee_value = item["employee"]["S"] print(item) if employee_value == alias: print(f"{alias} is an employee") else: print(f"{alias} is not an active employee")
方式2:改用boto3资源简化格式
使用boto3.resource替代client,它会自动将DynamoDB的类型格式转换为Python原生类型,代码更简洁:
def main(): alias = "jen" # 使用resource而非client ddb = boto3.resource("dynamodb") table = ddb.Table("testtable") get_ddb_item = table.get_item(Key={"employee": alias}) item = get_ddb_item["Item"] print(item) # 此时item["employee"]是原生字符串"jen" if item["employee"] == alias: print(f"{alias} is an employee") else: print(f"{alias} is not an active employee")
内容的提问来源于stack exchange,提问作者jenc
相关产品推荐
相关产品推荐

