Home > other >  Replacing old values in dictionary with new values
Replacing old values in dictionary with new values

Time:06-03

I have a dictionary as follows:

d =
{1.0: 86, 2.0: 4406, 3.0: 523, 4.0: 324, 5.0: 1641, 6.0: 863}

I want to scale the values present in the dictionary to the range (0,255) and replace the scaled values with the old ones. To do this I use the MinMaxScaler from sklearn. I do the following:

MinMaxScaler(feature_range=(0, 255)).fit_transform(np.array(list(distance.values())).reshape(-1,1)).astype(int)

Now the results for the above line of code is:

array([[  0],
       [254],
       [ 25],
       [ 14],
       [ 91],
       [ 45]])

I want the values in dictionary to be replaced with the values (output) presented above that is with the scaled values present in the array. The desired output should look like:

d =
{1.0: 0, 2.0: 254, 3.0: 25, 4.0: 14, 5.0: 91, 6.0: 45}

How can I achieve this? Thanks in advance!

CodePudding user response:

Since the new array is the same size as the dictionary, you could iterate through the dictionary and replace each element:

for index, (key, value) in enumerate(d.items()):
    d[key] = array[index]
  • Related