[英]Python ValueError when using SQLITE3 and dictionary
After I was able to successfully store values from a SQLITE database in a python dictionary. 在我能够成功地将SQLITE数据库中的值存储在python字典中之后。 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: 首先,Andy Hayden提供的解决方案可以正常工作,但是当我在代码中实现该解决方案时,我开始遇到以下错误:
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? 我是否还需要在循环的项目中添加“ .iterititems”? When I input the SQLITE data manually, and revert 'd.iteritems' back to 'd', the code works without a problem.
当我手动输入SQLITE数据并将“ d.iteritems”还原为“ d”时,代码可以正常工作。
Any suggestions would again be more than welcome! 任何建议将再次受到欢迎!
d
is a dictionary, so you need to iterate through its items for this to unpack correctly: d
是字典,因此您需要遍历其项才能正确解压缩:
[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. 注意:在python 3中,
d.keys()
返回一个集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.