【问题标题】:Formatting dicts and nested dicts格式化字典和嵌套字典
【发布时间】: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


    【解决方案1】:

    最终为我工作的是以下功能:

    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
    

    如果有人有更好的方法,请告诉我!

    【讨论】:

    • 投了反对票的人能否发表评论,解释您如何改进或替换我的解决方案?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多