[英]Formatting dicts and nested dicts
Amazon's DynamoDB requires specially formatted JSON when inserting items into the database. 将项目插入数据库时,Amazon的DynamoDB需要特殊格式的JSON。
I have a function that takes a dictionary and transforms values into a nested dict formatted for insertion; 我有一个函数,它需要一个字典并将值转换为格式化为插入的嵌套字典; the value is transformed into a nested dict where the nested key is the value's data type.
该值将转换为嵌套dict,其中嵌套键是值的数据类型。
For example, input like {'id':1, 'firstName':'joe'}
would be transformed to {'id': {'N':1}, 'firstName': {'S':'joe'}}
例如,将类似
{'id':1, 'firstName':'joe'}
输入转换为{'id': {'N':1}, 'firstName': {'S':'joe'}}
This is currently successful with this function: 目前,此功能成功完成:
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
I need to modify this function to handle values that might be dicts. 我需要修改此函数以处理可能是字典的值。
So, for example: 因此,例如:
{
'id':1,
'a':{'x':'hey', 'y':1},
'b':{'x':1}
}
Should be transformed to: 应转换为:
{
'id': {'N':1},
'a':{'M': {'x': {'S':'hey'}, 'y':{'N':1}}},
'b': {'M': {'x': {'N':1}}}
}
I'm thinking the correct way to do this must be to call the function from within the function right? 我在想正确的方法必须是从函数内部调用函数,对吗?
Note: I'm using Python 2.7 注意:我使用的是Python 2.7
What ultimately ended up working for me was the following function: 最终为我工作的是以下功能:
def format_row(self, row):
""" Accepts a dict, formats for DynamoDB insertion. """
formatted = {}
for k,v in row.iteritems():
if type(v) == dict:
v = self.format_row(v)
type_dict = {}
type_dict['M'] = v
formatted[k] = type_dict
else:
type_dict = {}
type_dict[ self.type_map[type(v)] ] = v
formatted[k] = type_dict
return formatted
If anyone has a better way of doing this, please let me know! 如果有人有更好的方法,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.