'Update nested dictionary with maxval calculation [suggestion]

I can achieve what I'm looking for, but I think there is a better method to get the result.

I'm working with a dict of dictionary like:

d = {0: {'Imp': 2.495577410636579}, 2: {'Imp': 2.2525405473189477}, 3: {'Imp': 2.295978990273124}, 4: {'Imp': 2.252531397995056}, 5: {'Imp': 2.2959971129346797}, 6: {'Imp': 2.273698009428239}, 7: {'Imp': 2.2737236004559938}, 8: {'Imp': 2.2039283340143205}, 9: {'Imp': 2.118908577523577}, 10: {'Imp': 1.9711305723637529}, 11: {'Imp': 2.440297052278874}, 12: {'Imp': 2.672508505522489}, 13: {'Imp': 2.2597460370958578}, 14: {'Ims': -0.8216131925248704}, 15: {'Ims': -1.5546877151372314}, 16: {'Imp': 2.2745760620390487}, 17: {'Imp': 2.243737059957979}, 18: {'Ims': -0.6699935461544082}}

what I need to do is to:

  • extract the maximum value of the nested dictionary
  • update the dictionary with a simple division value / maximum value extracted

I did like the following:

# extract the maximum value of the nested dictionary
d_max = max([max(b.values()) for a, b in d.items()])

# update the original dictionary with the calculation
for k, v in d.items():
    td = {}
    for kk, vv in v.items():
        a = vv / d_max
        td['index'] = a
    d[k].update(td)

it is working, but are there better and suggested method to obtain the result?

Thanks for any suggestion!



Solution 1:[1]

How about this:

d = {
    0: {'Imp': 2.495577410636579}, 
    2: {'Imp': 2.2525405473189477}, 
    3: {'Imp': 2.295978990273124}, 
    4: {'Imp': 2.252531397995056}, 
    5: {'Imp': 2.2959971129346797}, 
    6: {'Imp': 2.273698009428239}, 
    7: {'Imp': 2.2737236004559938}, 
    8: {'Imp': 2.2039283340143205}, 
    9: {'Imp': 2.118908577523577}, 
    10: {'Imp': 1.9711305723637529}, 
    11: {'Imp': 2.440297052278874}, 
    12: {'Imp': 2.672508505522489}, 
    13: {'Imp': 2.2597460370958578}, 
    14: {'Ims': -0.8216131925248704}, 
    15: {'Ims': -1.5546877151372314}, 
    16: {'Imp': 2.2745760620390487}, 
    17: {'Imp': 2.243737059957979}, 
    18: {'Ims': -0.6699935461544082},
}

max_value = max([max(d[num].values()) for num in d])  # 2.672508505522489
for k in d:
    for kk, vv in list(d[k].items()):
        d[k]['Index'] = vv / max_value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CJR