Skip to main content

How to use Gurobi variables as a dictionary index in Gurobipy




  • Simon Bowly
    Gurobi Staff Gurobi Staff

    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.

  • Saeid Ghafouri

    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}
  • Simon Bowly
    Gurobi Staff Gurobi Staff

    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.


Please sign in to leave a comment.