【问题标题】:Prepend all values in deeply nested dictionary在深度嵌套字典中添加所有值
【发布时间】:2020-05-17 07:06:49
【问题描述】:

我有一个深度嵌套的字典(任意键和值),例如:

data = {
    'a': {
        'path': '/a/a.txt'
    },
    'b': {
        'b1': {
            'path': '/b/b1/b1.txt'
        },
        'b2': {
            'path': '/b/b2/b2.txt'
        }
    }
    'c': {
        'c1': {
            'c12': {
                'path': '/c/c1/c12/c12.txt'
            }
        },
        'c2': {
            'c22': {
                'path': '/c/c1/c22/c22.txt'
            }
        },
        'c3': {
            'c32': {
                'path': '/c/c1/c32/c32.txt'
            }
        }
    }
    .
    .
    .
}

我的目标是在字典中的每个值前面加上一个特定的路径。所以基本上把上面的数据拿进去,对它进行操作:

def prepend(value, data):
    return magic

data = prepend('predir/z', data)

并让结果字典看起来像:

data = {
    'a': {
        'path': 'predir/z/a/a.txt'
    },
    'b': {
        'b1': {
            'path': 'predir/z/b/b1/b1.txt'
        },
        'b2': {
            'path': 'predir/z/b/b2/b2.txt'
        }
    }
    'c': {
        'c1': {
            'c12': {
                'path': 'predir/z/c/c1/c12/c12.txt'
            }
        },
        'c2': {
            'c22': {
                'path': 'predir/z/c/c1/c22/c22.txt'
            }
        },
        'c3': {
            'c32': {
                'path': 'predir/z/c/c1/c32/c32.txt'
            }
        }
    }
    .
    .
    .
}

我知道我可以像这样使用递归循环遍历字典:

def prepend(directory, config):
    for k, v in config.items():
        if isinstance(v, dict):
            prepend(directory, v)
        else:
            # do something

但是,我无法在迭代期间更改值。非常感谢任何和所有帮助!谢谢!

【问题讨论】:

  • else: # do something 中有什么?你如何尝试改变价值?您是否尝试更改 config[k] 而不是 v 的值?

标签: python python-3.x dictionary prepend


【解决方案1】:

else分支中,只需将前缀添加到现有值,并将其存储在key中:

def prepend(directory, config):
    for k, v in config.items():
        if isinstance(v, dict):
            prepend(directory, v)
        else:
            config[k] = directory + v
    return config

【讨论】:

  • 不知道我是怎么错过的!谢谢!
【解决方案2】:

你必须使用

else:
    config[k] = directory + config[k]

else:
    config[k] = directory + v

它会直接更改原始data 中的值,因此您不需要return config


顺便说一句:如果要保留原始数据,则必须在函数中创建new_config

def prepend(directory, config):
    new_config = {}
    for k, v in config.items():
        if isinstance(v, dict):
            new_config[k] = prepend(directory, v)
        else:
            new_config[k] = directory + v

    return new_config

new_data = prepend('predir/z', data)
print(data)
print(new_data)

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2017-04-30
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 2011-03-15
    相关资源
    最近更新 更多