不同深度的嵌套字典的更新值 [英] Update value of a nested dictionary of varying depth

查看:73
本文介绍了不同深度的嵌套字典的更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 dict update 的内容更新 dict dictionary1 而不覆盖 levelA 的方法

I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA

dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}}}
update={'level1':{'level2':{'levelB':10}}}
dictionary1.update(update)
print dictionary1
{'level1': {'level2': {'levelB': 10}}}

我知道 update 会删除 level2 中的值,因为它正在更新最低的 key level1.

I know that update deletes the values in level2 because it's updating the lowest key level1.

鉴于 dictionary1 和 update 可以有任何长度,我该如何解决这个问题?

How could I tackle this, given that dictionary1 and update can have any length?

推荐答案

@FM 的答案具有正确的总体思路,即递归解决方案,但有些特殊的编码和至少一个错误.我建议改为:

@FM's answer has the right general idea, i.e. a recursive solution, but somewhat peculiar coding and at least one bug. I'd recommend, instead:

Python 2:

import collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

Python 3:

import collections.abc

def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

当更新"有一个 k, v 项,其中 v 是一个 dict 时,这个错误就会出现> 和 k 原本不是正在更新的字典中的键——@FM 的代码跳过"了更新的这一部分(因为它在一个空的新 dict 上执行它未保存或任何地方返回刚刚失去当递归调用返回).

The bug shows up when the "update" has a k, v item where v is a dict and k is not originally a key in the dictionary being updated -- @FM's code "skips" this part of the update (because it performs it on an empty new dict which isn't saved or returned anywhere, just lost when the recursive call returns).

我的其他变化很小:当 .get 更快、更清晰地完成同样的工作时,没有理由使用 if/else 构造, 并且 isinstance 最好应用于抽象基类(而不是具体基类)以实现一般性.

My other changes are minor: there is no reason for the if/else construct when .get does the same job faster and cleaner, and isinstance is best applied to abstract base classes (not concrete ones) for generality.

这篇关于不同深度的嵌套字典的更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆