我要存储在货架的整数键。但是,当我尝试存储整数货架关键它给我一个错误

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

我代码:

#!/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()

有什么事在我的计划或搁置不支持整数钥匙呢?


修改1:

在节目我试图存储与ID的另一个字典作为一个重要的内部编号和名称的字典。然后试图将其存储在一个文件中。

我是否需要使用Recno中或队列DB的一起搁置?我是一个初学者,事情混淆。

让我知道,如果我不清楚我的问题。

感谢。

有帮助吗?

解决方案

在货架模块使用底层数据库包(如DBM,GDBM或bsddb)。

一个“货架”是一种持久性的,类似于字典的对象。与“DBM”数据库不同的是,在货架的值(不是键!)基本上可以是任意的Python对象 - 任何咸菜模块可以处理。这包括大多数类实例,递归类型,以及含有大量的共享子对象的对象。键是普通字符串。的例子部分给你的证明。

此应该工作。这是我在我的代码做 -

import shelve

#Create shelve
s = shelve.open('test_shelf.db')
try:
    s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
finally:
    s.close()

#Access shelve
s = shelve.open('test_shelf.db')
try:
    existing = s['key1']
finally:
    s.close()
print existing

更新::您可以尝试pickle模块。它不是一个键值数据库,但你总是可以建立自己的数据结构作为键值对,然后将其发送到pickle -

如果你有一个对象x,并打开过的写入一个文件对象楼,以酸洗对象的最简单的方法只需要一行代码

pickle.dump(x, f)

要再次unpickle对象,如果f是已经打开,用于读取一个文件对象:

x = pickle.load(f)

我听到cPicklepickle快得多。你可以试试这个,如果你有大量的数据存储。

其他提示

在您的示例数据库中的钥匙永远是整数,所以它应该工作的罚款将它们转换为字符串,

数据[STR(ID)] = { “ID”:ID, “名称”:名称}

我的测试代码

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top