Skip to main content

Use value of Var as dictionary key



1 comment

  • Jaromił Najman
    Gurobi Staff Gurobi Staff


    The addVars function returns a tupledict. As a consequence, the values of \(\texttt{s_var}\) in the

    for s_var in s_vars

    loop return the keys to the variables, i.e., values \(0-3\). Thus, the \(\texttt{quicksum}\)

    gp.quicksum([optimal_values[s_var] for s_var in s_vars])

    returns the sum over

    optimal_values[0], optimal_values[1], optimal_values[2], optimal_values[3]

    However, the second quicksum

    gp.quicksum([optimal_values[s_var.X] for s_var in s_vars.values()])

    actually accesses the variable objects because you loop over the variable objects as you use \(\texttt{s_vars.values()}\). This then sums the values

    optimal_values[s_var[0].X], optimal_values[s_var[1].X], optimal_values[s_var[2].X], optimal_values[s_var[3].X]

    This is the same as

    gp.quicksum([optimal_values[s_vars[s_var].X] for s_var in s_vars])

    This is OK as long as you can ensure that the variable solution values are integer and within the \(0-3\) range.

    Best regards,


Please sign in to leave a comment.