Skip to content

Instantly share code, notes, and snippets.

@filipelenfers
Forked from JamieCressey/dict_to_dynamodb_item.py
Last active October 10, 2019 19:10
Show Gist options
  • Save filipelenfers/57662882cf9d08952cd0f5f1fb4ba1b7 to your computer and use it in GitHub Desktop.
Save filipelenfers/57662882cf9d08952cd0f5f1fb4ba1b7 to your computer and use it in GitHub Desktop.
Coverts a standard Python3 dictionary to a Boto3 DynamoDB item
def dict_to_item(raw:dict):
return {
key: _dict_to_item_recurse(value)
for key, value in raw.items()
}
def _dict_to_item_recurse(raw):
if isinstance(raw, dict):
return {
'M': {
key: _dict_to_item_recurse(value)
for key, value in raw.items()
}
}
elif isinstance(raw, list):
return {
'L': [_dict_to_item_recurse(value) for value in raw]
}
elif isinstance(raw, str):
return {'S': raw}
elif isinstance(raw, bool):
return {'BOOL', raw}
elif isinstance(raw, (int, float)):
return {'N': str(raw)}
elif isinstance(raw, bytes):
return {'B', raw}
elif raw is None:
return {'NULL': True}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment