Skip to content

Instantly share code, notes, and snippets.

@JamieCressey
Created April 24, 2016 20:56
Show Gist options
  • Save JamieCressey/a3a75a397db092d7a70bbe876a6fb817 to your computer and use it in GitHub Desktop.
Save JamieCressey/a3a75a397db092d7a70bbe876a6fb817 to your computer and use it in GitHub Desktop.
Coverts a standard Python dictionary to a Boto3 DynamoDB item
def dict_to_item(raw):
if type(raw) is dict:
resp = {}
for k,v in raw.iteritems():
if type(v) is str:
resp[k] = {
'S': v
}
elif type(v) is int:
resp[k] = {
'I': str(v)
}
elif type(v) is dict:
resp[k] = {
'M': dict_to_item(v)
}
elif type(v) is list:
resp[k] = []
for i in v:
resp[k].append(dict_to_item(i))
return resp
elif type(raw) is str:
return {
'S': raw
}
elif type(raw) is int:
return {
'I': str(raw)
}
@jakariadev
Copy link

from boto3.dynamodb.types import TypeSerializer
serializer = TypeSerializer()
item = {"foo": "bar"}
dyn_item = {key: serializer.serialize(value) for key, value in item.items()}

This really works for me. Thanks a lot, @yousefcodes . I was Stack on it for 1 day. Much Appreciated. Is it possible to do as this works in Update items?

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