Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading