Changing specific values in a python dictionary

Advertisements

I have the following dictionary in python:

dict={('M1 ', 'V1'): 5,
 ('M1 ', 'V2'): 5,
 ('M1 ', 'V3'): 5,
 ('M1 ', 'V4'): 5,
 ('M2', 'V1'): 5,
 ('M2', 'V2'): 5,
 ('M2', 'V3'): 5,
 ('M2', 'V4'): 5,
 ('M3', 'V1'): 5,
 ('M3', 'V2'): 5,
 ('M3', 'V3'): 5,
 ('M3', 'V4'): 5}

For contextualization, "dict" is a matrix distance ((‘Source’, ‘Destination’): Value) for an optimization problem, and in conducting a sensitivity analysis, I want to make the distances from M1 so high that the model won’t choose it. Therefore, I want to get the python code to change the value of each line where M1 is a source.

>Solution :

First off, dict is a reserved keyword, so don’t use that as the name of your dictionary.

distances = {(...): ...,}

for source, destination in distances:
    if source == "M1 ":
        distances[(source, destination)] = 100000 # or something

Leave a ReplyCancel reply