Update nested dictionary value with same key's value one level up

Asked 3 months ago
Viewed 19 times


[{'x': 'ABC-1|ABD-5',
  'y': 8,
  'z': 2,
  'aa': {'az': 0.1001692265},
  'bb': {'z': 0.0816721693}}]

How can I update the nested dictionary's value for the same key such that it becomes:

[{'x': 'ABC-1|ABD-5',
  'y': 8,
  'z': 2,
  'aa': {'az': 0.1001692265},
  'bb': {'z': 2}}]

Any ideas?

Edit: Looking for a more dynamic solution where I could repurpose this for any dict with different keys

asked 3 months ago

Correct Answer

How about a recursive function?

d = {
    "x": "ABC-1|ABD-5",
    "y": 8,
    "z": 2,
    "aa": {"az": 0.1001692265},
    "bb": {"z": 0.0816721693},

def update(d, key, val):
    d[key] = val
    for k, v in d.items():
        if isinstance(v, dict):
            update(v, key, val)

update(d, "z", 2)
answered 3 months ago

Other Answer

Looks like you need

>>> d[0]['bb']['z'] = d[0]['z']

If you want to do this for every subkey, then try a dict comprehension

>>> {k:v if not isinstance(v, dict) 
         else {subkey: (subval if subkey not in d[0] else d[0][subkey]) 
               for (subkey, subval) in v.items()} 
     for k,v in d[0].items()}
answered 3 months ago