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.

>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()}

Leave a Reply