6

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'

SecretAgentMan
  • 1,895
  • 2
  • 13
  • 39
Georgios
  • 1,193
  • 5
  • 21

1 Answers1

5

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),
        var_type=INTEGER,
        ub=employeeDict[e].mitarbeiter_ist_formen,
    )
    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.

Stradivari
  • 1,414
  • 6
  • 14
  • 1
    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. – Georgios Feb 11 '20 at 13:17
  • 2
    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. – Stradivari Feb 11 '20 at 13:19