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")
# Set objective function
m.setObjective(x, gp.GRB.MINIMIZE)

# Add constraints
m.addConstr(my_dict[x] >= 1, name="c1")

# Optimize the model

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.keys()))
  1. Is there a solution to this for bounding values to a specific set?
  • $\begingroup$ Not familiar with Gurobi, but don't you need to provide the index of the $x$-variable? Something like x = m.addVar(list(my_dict.keys(), name="x"). $\endgroup$ Commented Mar 3, 2023 at 8:49
  • $\begingroup$ That's true, edited. $\endgroup$ Commented Mar 3, 2023 at 11:28
  • $\begingroup$ Does the answer below help in this? Also I understand it's example but constr in code doesn't make sense to me. Dictionary values are already greater than 1 and if x values are limited to keys the constr seems redundant. $\endgroup$ Commented Mar 3, 2023 at 12:23
  • $\begingroup$ No it doesn't. The above is just a dummy example. The question as mentioned is whether I can use variables in a dict or not? $\endgroup$ Commented Mar 4, 2023 at 0:18
  • 1
    $\begingroup$ @saeid-ghafouri, No, decision variables cant be used as index for any list/dictionary. you have to use it through a binary indexed over the key that turns to 1 for the key that matches with value of the variable. $\endgroup$ Commented Mar 5, 2023 at 21:36

1 Answer 1


First bounding of your vector variable $x$ over dict key set $I$
$ \sum_{i\in I} iz_i = x$
$ \sum_i z_i = 1$ where $z$ is binary.

The above 2 bounds $x$ to choose from $I$ and to use:
$\sum_{i\in I} z_iD_i$ where D is your dict.

Sample code below

D ={1:3, 2:5, 6:3.5, 8:4.2, 6:5.2}
model = Model('Index')
x = model.addVar(name='x')
z = model.addVars(D,vtype='b',name='z')

# constraints
C1 = model.addConstr(quicksum(d*z[d] for d in D) == x,name='C1')
C2 = model.addConstr(z.sum()==1, name='C2')
C3 = model.addConstr(quicksum(z[d]*D[d] for d in D) >= 2,name='C3')

obj = x
#obj = quicksum(z[d]*D[d] for d in D)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.