我想在 shelve 中存储一个整数键。但是当我尝试在 shelve 中存储整数键时,它给我一个错误
Traceback (most recent call last): File "./write.py", line 12, in data[id] = {"Id": id, "Name": name} File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__ self.dict[key] = f.getvalue() File "/usr/lib/python2.5/bsddb/__init__.py", line 230, in __setitem__ _DeadlockWrap(wrapF) # self.db[key] = value File "/usr/lib/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap return function(*_args, **_kwargs) File "/usr/lib/python2.5/bsddb/__init__.py", line 229, in wrapF self.db[key] = value TypeError: Integer keys only allowed for Recno and Queue DB's
My Code :
#!/usr/bin/python
import shelve
data = shelve.open("data.txt")
ans = 'y'
while ans == "y":
id = input("Enter Id : ")
name = raw_input("Enter name : ")
data[id] = {"Id": id, "Name": name}
ans = raw_input("Do you want to continue (y/n) ? : ")
data.close()
是我的程序有问题还是 shelve 根本不支持整数键?
编辑 1:
在程序中,我试图将 Id 和 Name 的字典存储在另一个以 Id 作为键的字典中。然后尝试将其存储在文件中。
我是否需要将 Recno 或 Queue DB 与搁置一起使用?我是初学者,事情很困惑。
如果我的问题不清楚,请告诉我。
谢谢。
最佳答案
在您的示例中,数据库中的键始终是整数,因此将它们转换为字符串应该可以正常工作,
data[str(id)] = {"Id": id, "Name": name}
我的测试代码
def shelve_some_data(filename):
db = shelve.open(filename, flag="c")
try:
# note key has to be a string
db[str(1)] = "1 integer key that's been stringified"
db[str(2)] = "2 integer key that's been stringified"
db[str(3)] = "3 integer key that's been stringified"
db[str(10)] = "10 integer key that's been stringified"
finally:
db.close()
def whats_in(filename):
db = shelve.open(filename, flag="r")
for k in db:
print("%s : %s" % (k, db[k]))
return
filename = "spam.db"
shelve_some_data(filename)
whats_in(filename)
和输出;它像字典一样工作,因此没有排序。
2 : 2 integer key that's been stringified
10 : 10 integer key that's been stringified
1 : 1 integer key that's been stringified
3 : 3 integer key that's been stringified
关于python - 如何搁置整数键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4013452/