AWS DynamoDB snippets

How to get item in DynamoDB with Python boto3 resource (and store response into a Pandas DF)

Please note that this snippet is part of the DynamoDB-Simpsons-episodes-full-example repository on GitHub.

Let's say you want to read the data from a DynamoDB table using the Primary Key of your simpsonsEpisodes table.

First of all, you have to create a Resource (follow these steps) and then you can use the following code to assign a value to the variables used below.

TABLENAME='simpsonsEpisodes'

The next step is to define a specific script to extract an item with particular valut of HASH key and SORT key.

table = dynamodbRes.Table(TABLENAME)

    response = table.get_item(
        Key={
            'No_Season': 1,
            'No_Inseason': 8
        }
    )

The response code and the data of the item are stored in the response variable.

print(response['Item'])
{'Title': 'The Telltale Head', 'ProdCode': '7G07', 'OriginalAirDate': '1990-02-25', 'USViewers(millions)': Decimal('28'), 'No_Season': Decimal('1'), 'DirectedBy': {'Rich Moore'}, 'No_Overall': Decimal('8'), 'WrittenBy': {'Mike Reiss', 'Matt Groening', 'Al Jean', 'Sam Simon'}, 'No_Inseason': Decimal('8')}

How to load data from DynamoDB get item to Pandas dataframe

To move data from the response variable to a Pandas dataframe it's easy, you just have to execute the following snippet:

df = pd.DataFrame.from_dict(response['Item'], orient='index')
    df=df.T
    df.head()
AWS DynamoDB to Pandas

Back to AWS DynamoDB cookbook page