【发布时间】:2016-11-20 04:13:43
【问题描述】:
在将项目插入数据库时,Amazon 的 DynamoDB 需要特殊格式的 JSON。
我有一个函数,它接受一个字典并将值转换为一个嵌套的 dict 格式以便插入;值被转换为嵌套的字典,其中嵌套的键是值的数据类型。
例如,{'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
【问题讨论】:
标签: python dictionary boto3