【问题标题】:Delete key at arbitrary depth in nested dictionary删除嵌套字典中任意深度的键
【发布时间】:2020-09-10 06:35:47
【问题描述】:

我的目标是从嵌套字典中删除一个值。

假设我有字典:d = {'a': {'b': {'c': 10, 'd': 4}}}

我知道我可以做到:del d['a']['b']['d']

但我有一个长度未知的嵌套键列表。如果我有列表['a', 'b', 'd'],我想产生与上述相同的行为。问题是我不知道使用上述语法的键列表的长度。

要使用相同的输入访问一个值,这很简单:

def dict_get_path(dict_in: Dict, use_path: List):
    # Get the value from the dictionary, where (eg)
    # use_path=['this', 'path', 'deep'] -> dict_in['this']['path']['deep']
    for p in use_path:
        dict_in = dict_in[p]
    return dict_in

但是我想不出任何类似的方法来删除一个项目而不重新构建整个字典。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    使用相同的循环,除了在最后一个键之前停止。然后用它从最里面的字典中删除。

    def dict_del_path(dict_in: Dict, use_path: List):
        # Loop over all the keys except last
        for p in use_path[:-1]:
            dict_in = dict_in[p]
        # Delete using last key in path
        del dict_in[use_path[-1]]
    

    【讨论】:

    • 啊,我没想到 Python 中的一切都是引用。下降到字典仍然引用同一个字典,而不是定义任何新的东西,所以这就是它起作用的原因。简单的解决方案——谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2011-02-01
    • 2017-03-08
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多