Input dictionary
d = {'PQR':{"LMN":1.345,'PST':1.278,'BQR':2.345,'RMT':9.867},
'HGE':{'VRM':1.765,'TRM':1.567,'FRM':1.456,'DRM':1.678}}
Is there any way to normalize the nested dictionary values in the range [0,1] using this formula
(value - min(x))/(max(x)- min(x))
However, for normalization, min and max values should find in every inner dictionary. Expected Output
output = {'PQR':{"LMN":0.0078006752823378675,'PST':0.0,'BQR':0.12422866457096288,'RMT':1.0},
'HGE':{'VRM':1.0,'TRM':0.3592233009708738,'FRM':0.0,'DRM':0.7184466019417476}}
CodePudding user response:
You can loop the inner dicts and mutate them accordingly. An example approach below:
d = {'PQR': {"LMN": 1.345, 'PST': 1.278, 'BQR': 2.345, 'LMN': 9.867},
'HGE': {'VRM': 1.765, 'TRM': 1.567, 'FRM': 1.456, 'DRM': 1.678}}
# Find the normalized value
fn = lambda value, x_max, x_min: (value - x_min) / (x_max - x_min)
# In each inner dict
for _d in d.values():
# find min and max values
max_x = max(_d.values())
min_x = min(_d.values())
# normalize each value in the dict
for k, v in _d.items():
_d[k] = fn(v, max_x, min_x)
print(d)
Gives you an output like below:
{'PQR': {'LMN': 1.0, 'PST': 0.0, 'BQR': 0.12422866457096288}, 'HGE': {'VRM': 1.0, 'TRM': 0.3592233009708738, 'FRM': 0.0, 'DRM': 0.7184466019417476}}