boltons icon indicating copy to clipboard operation
boltons copied to clipboard

dict rupdate()

Open kurtbrose opened this issue 8 years ago • 4 comments

def recursive_update(a, b):
    'dict.update(), but recurse when both values are dicts'
    for k, v in b.items():
        if v.__class__ is dict and a.get(k).__class__ is dict:
            a[k] = _recursive_update(a[k], v)
        else:
            a[k] = b[k]
    return a

Simple easy to understand idea I think. Tricky enough that people are messing it up though: http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth

kurtbrose avatar May 04 '17 20:05 kurtbrose

simple enough that it could perhaps use stack-of-dicts instead of recursion

kurtbrose avatar May 04 '17 20:05 kurtbrose

Potentially duplicate of https://github.com/mahmoud/boltons/issues/81, Or maybe just touches https://github.com/mahmoud/boltons/issues/81#issuecomment-249414209?

tuukkamustonen avatar May 05 '17 11:05 tuukkamustonen

Oh, that's a good point!

This might just be a special case of remerge([dict_a, dict_b]).

kurtbrose avatar May 05 '17 17:05 kurtbrose

If remerge is available, maybe a better way to handle this would be as a documented use-case of remerge.

def recursive_update(a, b):
   return remerge([a, b])

kurtbrose avatar May 05 '17 17:05 kurtbrose