-1

Consider:

[{'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

renaudb3
  • 78
  • 8
  • 2
    `d['bb']['z'] = d['z']` ? – rafaelc Jun 05 '22 at 00:28
  • @rafaelc Get a error ``` TypeError: list indices must be integers or slices, not str ``` Also looking for a more dynamic solution that I could reuse for other dicts :-) Will clarify that in an edit – renaudb3 Jun 05 '22 at 00:35
  • You are probably trying to emulate [pointers in Python](https://stackoverflow.com/questions/3106689/pointers-in-python), which isn't a straightforward thing to do. – metatoaster Jun 05 '22 at 01:11

3 Answers3

1

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)
Blackgaurd
  • 608
  • 6
  • 15
0

This will do what you want:

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

a['bb']['z'] = 2

print(a)
0

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()}
rafaelc
  • 57,686
  • 15
  • 58
  • 82