递归迭代和修改dict

时间:2014-10-22 21:56:42

标签: python

我有一个JSON这样的文件:

{
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": [
                "bottom.key1": "one",
                "bottom.key2": "two",
                ]
}

我需要存储一个不允许我存储句点(.)的数据结构。如何遍历此JSON结构,以便将每个.个匹配项替换为_?最终结果将是:

{
    "top_key1": {
                "bottom_key1": "one",
                "bottom_key2": "two"
                },
    "top_key2": [
                "bottom_key1": "one",
                "bottom_key2": "two",
                ]
}

JSON文件可以嵌套多个(未知)时间,值也可以.,但我不希望它们被_替换。此外," top_key2"的价值是一个列表,应该保留。

1 个答案:

答案 0 :(得分:3)

我认为不是太难,只需使用isinstance检查当前值是否是另一个字典:

nested_dict = {
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": {
                "bottom.key1": "one",
                "bottom.key2": "two",
                }
}

def replace_dots(nested_dict):
    result_dict = {}
    for key, val in nested_dict.items():
        key = key.replace('.', '_')
        if isinstance(val, dict):
            result_dict[key] = replace_dots(val)
        else:
            result_dict[key] = val
    return result_dict

fixed = replace_dots(nested_dict)

fixed
Out[4]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'},
 'top_key2': {'bottom_key1': 'one', 'bottom_key2': 'two'}}

我不确定我是否完全理解您的编辑,作为您的示例列表 仍然有一个键值结构,但添加一个额外的案件来处理 列表非常简单:

nested_dict2 = {
    "top_key1": {
                "bottom.key1": "one",
                "bottom.key2": "two"
                },
    "top_key2": ["list.item1", "list.item2"]
}

def replace_dots(nested_dict):
    result_dict = {}
    for key, val in nested_dict.items():
        key = key.replace('.', '_')
        if isinstance(val, dict):
            result_dict[key] = replace_dots(val)
        elif isinstance(val, list):
            cleaned_val = [v.replace('.', '_') for v in val]
            result_dict[key] = cleaned_val
        else:
            result_dict[key] = val
    return result_dict

replace_dots(nested_dict2)
Out[7]: 
{'top_key1': {'bottom_key1': 'one', 'bottom_key2': 'two'},
 'top_key2': ['list_item1', 'list_item2']}