# Creating a Decision Variable in Python-MIP with Dictionaries

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'

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

x = {
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.

• 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. Feb 11 '20 at 13:17
• 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. Feb 11 '20 at 13:19