I have already seen in the Python-MIP documentation on how to implement a variable with multiple indices. In each example I read, this is done with the use of lists and integers as indices.

This is how I implement a variable that I needed in the beginning:

x = [[[model.add_var(name='x({},{},{})'.format(e,s,a),var_type=INTEGER,ub = employeeDict[e].mitarbeiter_ist_formen)
   for e in employeeDict] for s in demandBelongingToShiftDict] for a in demandAppendedWithShiftDict]

But got the following error:

TypeError: list indices must be integers or slices, not str

Since the index a is a string.

Now I know that in Python is impossible to search within a list with strings as indices. This is why I would like to use dictionaries:

x = {{{model.add_var(name='x({},{},{})'.format(e,s,a),var_type=INTEGER,ub = employeeDict[e].mitarbeiter_ist_formen)
   for e in employeeDict} for s in demandBelongingToShiftDict} for a in demandAppendedWithShiftDict}

Unfortunately, I am getting the following error:

TypeError: unhashable type: 'set'


1 Answer 1


Haven't used python-mip but to create multi-index variables I usually do:

x = {
    (e, s, a): model.add_var(
        name="x({},{},{})".format(e, s, a),
    for e in employeeDict
    for s in demandBelongingToShiftDict
    for a in demandAppendedWithShiftDict

and access it by x[e, s, a].

You are doing set instead of dict comprehensions because you are not creating key-value pairs.

  • 1
    $\begingroup$ This is great. I implemented your idea and now I am not getting any errors. I will test it further and report back. The only thing I do not understand in your code is, that you only use the braces {} once. I thought I would have to do this 3 times. $\endgroup$
    – Georgios
    Commented Feb 11, 2020 at 13:17
  • 2
    $\begingroup$ I am only creating a single dictionary where the key is a (e, s, a) tuple and the value is the corresponding variable, I guess you could also nest multiples dictionaries (like the example with lists) but I don't think that is a good (readable) option. $\endgroup$
    – Stradivari
    Commented Feb 11, 2020 at 13:19

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.