Prashanth
Prashanth

Reputation: 141

Handling response from DynamoDB - Python

I'm receiving following data from DynamoDB as a response to client scan API call.

Data = [{'id': {'S': '5'},
         'FirstName': {'S': 'Prashanth'},
         'LastName': {'S': 'Wadeyar'},
         'ClientName': {'S': 'Test'}}]

I want to handle this response and get the output as

{'FirstName':'Prashanth', 'LastName': 'Wadeyar', 'ClientName': 'Test'}

I can handle it by separating it like

for field_obj in data:
    obj = (field_obj['FirstName'])

but to get value of Firstname, Key 'S' may differ for each object. like boolean string, list etc.

is there a easy way to get the key and value pairs.

Upvotes: 0

Views: 2663

Answers (3)

Prashanth
Prashanth

Reputation: 141

Above answer from Mayank seems to work well, but I also wanted to map fields I want to return in a list. Hence I mapped field and then was able to get the result I was looking for

FIELD_MAP = ['firstName', 'lastName',
               'clientName']

    for field_obj in response['Items']:
        for key in FIELD_MAP:
            if field_obj.get(key):
                obj = (field_obj.get(key))
                for i in obj:
                    value = obj[i]
                db_result.append({key: value})
    print(db_result)

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

Something like this could work, where you don't need to care about the internal keys(S in your case):

In [1018]: d = {}

In [1016]: for i in Data: 
      ...:     for k,v in i.items():
      ...:         if k != 'id':
      ...:             if isinstance(v, dict): 
      ...:                 for j, val in v.items(): 
      ...:                     d[k] = val 
      ...:                  

In [1024]: d                                                                                                                                                                                                
Out[1024]: {'FirstName': 'Prashanth', 'LastName': 'Wadeyar', 'ClientName': 'Test'}

Upvotes: -1

Andrey
Andrey

Reputation: 60065

If you don't want to bring external dependencies you can use Table class as described here.

import boto3

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')

response = table.get_item(
    Key={
        'username': 'janedoe',
        'last_name': 'Doe'
    }
)
item = response['Item']
print(item)

Expected Output:

{u'username': u'janedoe',
 u'first_name': u'Jane',
 u'last_name': u'Doe',
 u'account_type': u'standard_user',
 u'age': Decimal('25')}

But my personal preference everytime I hear about Python and DynamoDB is to use PynamoDB: https://pynamodb.readthedocs.io/en/latest/ which is sort of an ORM for DynamoDB.

Upvotes: 2

Related Questions