How to update DynamoDB table with DICT data type (boto3)

≡放荡痞女 提交于 2020-02-23 13:41:15

问题


I created a DynamoDB table that is used for storing metadata, with different attributes for different types of data (file size, date, etc., as separate attributes).

I am trying to take a Python3 dictionary and use it as the source for a bunch of attributes that need to be uploaded to the table. So far, I've been able to successfully upload the entire dictionary as one attribute, but I want each key:value pair to be its own attribute in the database. In other words, each key:value pair from the Python3 dictionary should end up as its own key:value pair in the DynamoDB table. I'm aware my code below is not designed to that so far.

Here is my code so far:

file_attributes = dict(file.items())

    # Add all metadata to DynamoDB:
    response = table.update_item(
        UpdateExpression="set File_attributes = :f,"
        Key={
            'file_name': key,
        },
        ExpressionAttributeValues={
            ':f': file_attributes,

        },
        ReturnValues="UPDATED_NEW"
    )

回答1:


I think you are looking for something along these lines:

update_expression = 'SET {}'.format(','.join(f'#{k}=:{k}' for k in file))
expression_attribute_values = {f':{k}': v for k, v in file.items()}
expression_attribute_names = {f'#{k}': k for k in file}

response = table.update_item(
    Key={
        'file_name': key,
    },
    UpdateExpression=update_expression,
    ExpressionAttributeValues=expression_attribute_values,
    ExpressionAttributeNames=expression_attribute_names,
    ReturnValues='UPDATED_NEW',
)

I modified your example to generate update expression dynamically using both ExpressionAttributeValues and ExpressionAttributeNames. Usage of name aliases was required, because we do not know what are the names of the items inside file dictionary. Generated update expression will contain set statement for each top-level key inside file dictionary. Attribute names are prefixed with # sign, and attribute values are prefixed with : sign.



来源:https://stackoverflow.com/questions/52367094/how-to-update-dynamodb-table-with-dict-data-type-boto3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!