dsaiztc
4/19/2017 - 8:47 AM

Parse DynamoDB element to python dict.

Parse DynamoDB element to python dict.

# -*- coding: utf-8 -*-


def parse_dynamodb_dict(dynamodb_dict):

    def parse_value(value):
        value_mapper = {
            'S': unicode,
            'N': float,
            'B': str,
            'SS': lambda x: [unicode(item) for item in x],
            'NS': lambda x: [float(item) for item in x],
            'BS': lambda x: [str(item) for item in x],
            'M': parse_dynamodb_dict,
            'L': lambda x: [parse_value(item) for item in x],
            'NULL': lambda x: None if bool(x) else '',
            'BOOL': lambda x: x in [True, 'True', 'true', '1', 1, 'yes']
        }
        key = value.keys()[0]  # It's a dictionary with one key
        return value_mapper[key](value[key])

    result_dict = {}

    for key in dynamodb_dict:
        result_dict[key] = parse_value(dynamodb_dict[key])

    return result_dict