Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
    )
like image 779
Andrew6850 Avatar asked Sep 17 '18 11:09

Andrew6850


1 Answers

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.

like image 83
Marcin Sucharski Avatar answered Sep 27 '22 23:09

Marcin Sucharski