0
将项目插入数据库时,Amazon的DynamoDB需要特殊格式的JSON。格式化字典和嵌套字典
我有一个函数,它需要一个字典并将值转换为格式化插入的嵌套字典;该值将转换为嵌套字典,其中嵌套键是值的数据类型。
例如,像{'id':1, 'firstName':'joe'}
输入将被转换成{'id': {'N':1}, 'firstName': {'S':'joe'}}
这是目前该功能成功:
type_map = {
str:'S', unicode:'S', dict:'M',
float:'N', int:'N', bool:'BOOL'
}
def format_row(self, row):
""" Accepts a dict, formats for DynamoDB insertion. """
formatted = {}
for k,v in row.iteritems():
type_dict = {}
type_dict[ self.type_map[type(v)] ] = v
formatted[k] = type_dict
return formatted
我需要修改这个函数来处理,可能是类型的字典值。
因此,举例来说:
{
'id':1,
'a':{'x':'hey', 'y':1},
'b':{'x':1}
}
应转化为:
{
'id': {'N':1},
'a':{'M': {'x': {'S':'hey'}, 'y':{'N':1}}},
'b': {'M': {'x': {'N':1}}}
}
我想正确的方法来做到这一点必须从功能权限内调用该函数?
注:我使用Python 2.7
谁可以降低评论请留下评论,解释您可能会改进或替换我的解决方案吗?谢谢! –