How to use Gurobi variables as a dictionary index in Gurobipy
AnsweredHello Gurobi team,
I want to model a problem that one of my variables needs to be used as an index of a dictionary in my constraints. Here is a minimal code that shows an example situation:
import gurobipy as gp
# Create a new Gurobi model
m = gp.Model()
my_dict = {1: 2, 3: 4, 5: 6}
# Create decision variables
x = m.addVar(name="x")
m.update()
# Set objective function
m.setObjective(x, gp.GRB.MINIMIZE)
# Add constraints
m.addConstr(my_dict[x] >= 1, name="c1")
# Optimize the model
m.optimize()
in this example variable x in the constraint is used as the index of my_dict dictionary. However, the above code will result in the following error:
KeyError: <gurobi.Var x>
1. Is there a workaround to solve this and be able to use variables as indexes?
Another thing I also need for the above formulation is to be able to bound value of varialbe dicts to keys in the my_dict, e.g. if there were some options like this:
model.addVar(name='x', vtype=GRB.INTEGER, set=list(my_dict.values()))
2. Is there a solution to this for bounding values to a specific set?

Hi Saeid,
No, you cannot use variables as keys. I am not sure I understand how this would help you here, could you clarify what you are trying to achieve? Maybe by writing down the mathematical formulation you are trying to produce?
To your second question (and perhaps this will resolve both queries), the traditional approach to modeling with gurobipy is to link an index set to a set of variables using model.addVars. For example the following code:
indices = [1, 2, 3]
x = model.addVars(indices, name=x)creates "x" as a dictionary which maps each entry in indices to a Gurobi variable:
{
1: <gurobi.Var x[1]>,
2: <gurobi.Var x[2]>,
3: <gurobi.Var x[3]>,
}You can then use x[1], x[2], and so on when creating constraints.
0 
Hi Simon,
Thank you for your response. I have a set of constants with different values depending on the chosen value for variable x, exactly like the above case, for now I have stored them in a dictionary for indexing. Maybe the only option is to add them one by one as a separate variable with a separate constraint. I mean adding each index of the following dictionary as a separate constraint with it's corresponding value from the dict.
my_dict = {1: 2, 3: 4, 5: 6}
0 
Hi Saeid,
If you are looking for a mapping in your model based on this dictionary, i.e. if x = 1 then y = 2, if x = 3 then y = 4, etc, then yes, you would need to introduce binary variables which encode which "case" you are in. Those auxiliary binary variables could be tied to the values of x and y using indicator constraints.
0
Please sign in to leave a comment.
Comments
3 comments