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
誰可以降低評論請留下評論,解釋您可能會改進或替換我的解決方案嗎?謝謝! –