如何将变量正确传递到此boto3 batch_get_item函数中?

时间:2017-03-09 02:36:13

标签: python boto3

这里可以看到一个小例子,介绍如何传递batch_get_item

的硬编码值

Is there a Python API for submitting batch get requests to AWS DynamoDB?

,文档在这里

http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Client.batch_get_item

但我很难相信这是经验丰富的python用户将密钥传递给函数的方式。是否可以将一个字符串(ids)列表传入Keys数组,这是如何完成的?

1 个答案:

答案 0 :(得分:0)

您可以使用列表推导来创建需要作为batch_get_item参数传递给Keys的值。像这样的东西会起作用:

# assume ids is a list of strings representing the ids you want to retrieve
# also assume that the primary key is called primary_key
keys = [{'primary_key': {'S': i}} for i in ids]
db_client.batch_get_item(
    RequestItems = {
        "my_table": {
            "Keys": keys
        }
    }
)

如果keys的值为['foo', 'bar', 'fie', 'baz'],则上述代码中keys的值为:

[{'primary_key': {'S': 'foo'}},
 {'primary_key': {'S': 'bar'}},
 {'primary_key': {'S': 'fie'}},
 {'primary_key': {'S': 'baz'}}]