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

Python update multilevel dictionary subitems having specific attribute/key

Assume I have database-like dictionary, where each item is also dictionary.
For example:

{
 'peter' : { 'age' : 28, 'department' : 3857 },
 'helga' : { 'department' : 57, 'occupancy' : 'graphics' },
 'eugene' : { 'age' : 48, 'department' : 12, 'role' : 'teamlead' }
 }

I want update all ages to 30, but only those entries that already have ‘age’. The above example should look like this after update:

{
 'peter' : { 'age' : 30, 'department' : 3857 },
 'helga' : { 'department' : 57, 'occupancy' : 'graphics' },
 'eugene' : { 'age' : 30, 'department' : 12, 'role' : 'teamlead' }
 }

Of course it is possible to do with nested fors and ifs, checking whether 'age' in entry, but I believe should be elegant pythonic way.
I guess it should be something with generator, but can’t figure how to do it right.

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

>Solution :

You could use a dict comprehension to create a new dictionary, but it is much simpler and more direct to just use a for loop.

res = {k : v | ('age' in v and {'age': 30} or {}) for k, v in d.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