Search code examples
pythoniterable-unpackinggurobi

Trying to define a 6 dimensional variable and I get too many values to unpack error


I am trying to use gurobi library in python (gurobi is an optimization library ) I got this error ---- Value Error: too many values to unpack

I'm trying to define a 6 dimensional variable in python. I defined each dimension as a list the dimensions were games, shifts, hours, pits, order1 and order2 Since only some combinations of these 6 dimensions are valid I defined combo as tuplelist to specify which combos exist. Then I wanted to define variables with the valid combos. Some of the objects like tuplelist and addVar comes with gurobipy library
The python code is :

from gurobipy import*
m=Model('mymodel')

combo, oi =multidict( {'(1,1,bj,1,1,1)': 100,
  '(1,1,bj,1,1,2)':200,
  '(1,1,bj,1,1,3)':200,
  '(1,1,bj,1,2,1)':50,
  '(1,1,bj,1,2,2)':70,
  '(1,1,bj,1,2,3)':70,
  '(1,1,cr,1,1,1)':400,
  '(1,1,cr,1,1,2)':450})

combo =tuplelist(['(1,1,bj,1,1,1)',
  '(1,1,bj,1,1,2)',
  '(1,1,bj,1,1,3)',
  '(1,1,bj,1,2,1)',
  '(1,1,bj,1,2,2)',
  '(1,1,bj,1,2,3)',
  '(1,1,cr,1,1,1)',
  '(1,1,cr,1,1,2)'])

x={}
for s,t,i,p,n,m in combo:
    x[s,t,i,p,n,m] = m.addVar(vtype=GRB.BINARY, obj=oi[s,t,i,p,n,m],name=s+","+t+","+i+","+p+","+n+","+m)

Solution

  • Your "combo" variable is a string which you can't unpack into multiple variables. Your code also, if your code did run, the "m" variable is used to store your model, would be overwritten in the for loop.

    from gurobipy import *
    model=Model('mymodel')
    
    combos, oi =multidict( {
        (1,1,'bj',1,1,1):100,
        (1,1,'bj',1,1,2):200,
        (1,1,'bj',1,1,3):200,
        (1,1,'bj',1,2,1):50,
        (1,1,'bj',1,2,2):70,
        (1,1,'bj',1,2,3):70,
        (1,1,'cr',1,1,1):400,
        (1,1,'cr',1,1,2):450})
    
    x={}
    for combo in combos:
        x[combo] = model.addVar(vtype=GRB.BINARY, 
                                      obj=oi[combo],
                                      name=".".join(map(str, combo)))