0

After I was able to successfully store values from a SQLITE database in a python dictionary. However, when trying to process these values, I am getting the following error:

'Traceback (most recent call last):
   File "transportation problem.py", line 20, in <module>
   I = set([i for (i,k) in d])
ValueError: too many values to unpack

Does this indicate a problem with my source database, or is my code flawed?

import sqlite3 as lite
import sys
from gurobipy import *

con = lite.connect('transport.sqlite')

produce = {1:[2,4], 2:[1,2,3], 3:[2,3,4]}

d = {}
with con:

cur = con.cursor()    
cur.execute('SELECT idcustomer,idfactory,distance FROM distance')
result = cur.fetchall()
for idcustomer, idfactory, distance in result:
      d["({},{})".format(idcustomer, idfactory)] = distance
      I = set([i for (i,k) in d])
      K = set([k for (i,k) in d])
      J,M = multidict({1:3000, 2:3000, 3:3000}) 

Any help is highly appreciated!

Edit: 

The solution provided by Andy Hayden worked fine at first, but when I implemented it into my code, I started getting the following error:

c[i,j,k] = cost[i,j] * weight[k]
KeyError: ('1,1', 1)

The code I posted initially continues as follows:

 produce = {1:[2,4], 2:[1,2,3], 3:[2,3,4]}  
 K, weight = multidict({1:5, 2:2, 3:3, 4:4})            
      cost = {(1,1):4,  (1,2):6, (1,3):9,        
              (2,1):5,  (2,2):4, (2,3):7,
              (3,1):6,  (3,2):3, (3,3):4,
              (4,1):8,  (4,2):5, (4,3):3,
              (5,1):10, (5,2):8, (5,3):4,
              }
      c = {}
      for i in I:
        for j in J:
           for k in produce[j]:
               c[i,j,k] = cost[i,j] * weight[k]

Do I need to add '.iterititems' to the loop's items as well? When I input the SQLITE data manually, and revert 'd.iteritems' back to 'd', the code works without a problem.

Any suggestions would again be more than welcome!

1 Answer 1

1

d is a dictionary, so you need to iterate through its items for this to unpack correctly:

[i for (i, k) in d.items()]
[i for (i, k) in d.iteritems()]

By default you iterate over its keys:

for k in d:  # equivalent to for k in d.keys()

Though actually you don't need the list comprehension here:

I = set(d)  # equivalent to set(d.keys())

will give you the set of keys. Note: In python 3, d.keys() returns a set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.