Python - 递归转换为字典列表中的字符串

时间:2018-04-02 18:27:03

标签: python python-3.x python-2.7 amazon-dynamodb

我有一个字典列表,在字典中有混合数据类型,即str,int,float,dict,list等。所以,我想确保每个深度的dict中的每个项都转换为字符串if它不是int或str,即我希望它被放入DynamoDB中。这是我一直在尝试的代码:

  def to_map(data):
    if(type(data) == list):
        for item in data:
            to_map(item)


    if type(data) == dict:    
        for attr in data:
            to_map(data[attr])

    if (type(data) != str) and (type(data) != int):
        return str(data) 

    return data

4 个答案:

答案 0 :(得分:1)

当你在字典上循环时,你只能得到键,而不是值。此外,自str(my_str) == my_str起,您无需在转换之前检查值是否为str。另外,请使用isinstance代替type(x) == ?。你在寻找这样的东西吗?

def to_map(data):
    if isinstance(data, list):
        return [to_map(x) for x in data]
    elif isinstance(data, dict):
        return {to_map(key): to_map(val) for key, val in data.items()}
    elif isinstance(data, int) and not isinstance(data, bool):
        return data
    else:
        return str(data)

答案 1 :(得分:0)

我假设你的意思是每个深度",你仍希望仍然遍历任何dictlist以达到下一个级别。为此,您可以使用递归检查理解中的类型。然后,该函数可以映射到您的词典列表:

def convert(structure, lookup = {int:str, float:str, bool:str, set:str, str:str}):
   return {lookup[type(a)](a):lookup.get(type(b), convert)(b) for a, b in structure.items()}

data = [{"val1":100, "val3":True, 200:{"val2":{200:{"new_depth":{"last_val":23.233, "second_last":"new_str"}}}}}]
last_result = list(map(convert, data))

输出:

[{'val3': 'True', '200': {'val2': {'200': {'new_depth': {'last_val': '23.233', 'second_last': 'new_str'}}}}, 'val1': '100'}]

答案 2 :(得分:0)

如果可能的话,这会将所有值转换为str除了int:

def to_map(iterable):
    if type(iterable) == list:
        return [str(item) if (type(item) not in [dict,str,list,int]) else to_map(item) for item in iterable ]
    elif type(iterable) == dict:
        return dict([[item,str(iterable[item])] if type(iterable[item]) not in [dict,str,list,int] else [item,to_map(iterable[item])] for item in iterable])
    elif type(iterable) == int:
        return iterable
x = {'1':2,'2':{'5':6,'6': False,'7':[1,2,3,4.55454]}}

print(to_map(x))
>> {'1': 2, '2': {'5': 6, '6': 'False', '7': [1, 2, 3, '4.55454']}}

答案 3 :(得分:0)

您应该使用json包和json.dumps字典。这将创建一个带有您的字典的json字符串,您可以将其作为JSON文档存储在dynamoDB中,或者如果您愿意,可以直接作为字符串存储。在这种情况下,您可以稍后阅读它并json.loads将其重新打印到python词典中。

使用JSON还意味着,如果您需要与其他产品或应用程序进行交互,将来您的兼容性问题会更少。

相关问题