是的,我就这样一件事使用了qlite3。 字典价值必须首先通过:
import sqlite3
import pickle
import collections
class DBDict(collections.MutableMapping):
Database driven dictlike object (with non-persistent in-memory option).
def __init__(self, db_filename= :memory: , **kwds):
self.db = sqlite3.connect(db_filename)
self.db.text_factory = str
try:
self.db.execute( CREATE TABLE dict (key text PRIMARY KEY, value text) )
self.db.execute( CREATE INDEX key ON dict (key) )
self.db.commit()
except sqlite3.OperationalError:
pass # DB already exists
self.update(kwds)
def __setitem__(self, key, value):
if key in self:
del self[key]
value = pickle.dumps(value)
self.db.execute( INSERT INTO dict VALUES (?, ?) , (key, value))
self.db.commit()
def __getitem__(self, key):
cursor = self.db.execute( SELECT value FROM dict WHERE key = (?) , (key,))
result = cursor.fetchone()
if result is None:
raise KeyError(key)
return pickle.loads(result[0])
def __delitem__(self, key):
if key not in self:
raise KeyError(key)
self.db.execute( DELETE FROM dict WHERE key = (?) , (key,))
self.db.commit()
def __iter__(self):
return iter([row[0] for row in self.db.execute( SELECT key FROM dict )])
def __repr__(self):
list_of_str = [ %r: %r % pair for pair in self.items()]
return { + , .join(list_of_str) + }
def __len__(self):
return len(list(iter(self)))
>>> d = DBDict(raymond= red , rachel= blue )
>>> d
{ rachel : blue , raymond : red }
>>> d[ critter ] = ( xyz , [1,2,3])
>>> d[ critter ]
( xyz , [1, 2, 3])
>>> len(d)
3
>>> list(d)
[ rachel , raymond , critter ]
>>> d.keys()
[ rachel , raymond , critter ]
>>> d.items()
[( rachel , blue ), ( raymond , red ), ( critter , ( xyz , [1, 2, 3]))]
>>> d.values()
[ blue , red , ( xyz , [1, 2, 3])]
以上将存放在单一档案中。 你们可以把物体当作普通字典。 由于这些价值观在单一领域被采纳,因此,qlite胜出给你任何额外的质疑选择。 其他公寓储存将受到类似的限制。 如果你需要写问题,反驳等级结构,考虑使用NSQL数据库。