Skip to content

Instantly share code, notes, and snippets.

@joshwolff1
Created March 19, 2020 04:42
Show Gist options
  • Save joshwolff1/c4f3bf59e9e3dbc8912c28624589277d to your computer and use it in GitHub Desktop.
Save joshwolff1/c4f3bf59e9e3dbc8912c28624589277d to your computer and use it in GitHub Desktop.
Convert Lambda / AWS Stream Dictionary to Regular Dictionary
from decimal import *
def recursive_get_dict(my_dict, use_decimal=True):
"""
:param my_dict: The dict to be converted, which is assumed to come from the record from the DynamoDB stream
:param use_decimal: Whether or not to use Decimal or int for the type for the number
:return: A dictionary converted from this format {"username" : {"S" : "beto"}} to this format {"username": "beto"}
"""
if type(my_dict) is not dict:
return my_dict
if my_dict.get('L', None) is not None:
my_dict = list(my_dict['L'])
new_list = []
for item in my_dict:
new_list.append(recursive_get_dict(item))
return new_list
elif my_dict.get('BOOL', None) is not None:
return bool(my_dict['BOOL'])
elif my_dict.get('S', None) is not None:
return str(my_dict['S'])
elif my_dict.get('SS', None) is not None:
return set(my_dict['SS'])
elif my_dict.get('NS', None) is not None:
return set(my_dict['NS'])
elif my_dict.get('N', None) is not None:
return Decimal(my_dict['N']) if use_decimal is True else int(my_dict['N'])
elif my_dict.get('M', None) is not None or type(my_dict) is dict:
my_dict = my_dict.get('M', my_dict)
new_dict = {}
for key in my_dict.keys():
new_dict[key] = recursive_get_dict(my_dict[key])
return new_dict
return {}
@joshwolff1
Copy link
Author

In AWS, sometimes streams are formatted to indicate the type.

e.g. New and old item streams from DynamoDB to Lambda will be formatted like {"username" : {"S" : "beto"}} and {"count" : {"N" : "0"}}. This removes the type strings and converts the dictionaries to dictionaries without the type strings: in this case, {"username" : "beto"} and {"count" : "0"}, respectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment