dictionary - object storage in python that allow tuples as keys -
i searching object storage in python allows me store dictionary having tuple
s keys. tried shelve , shove, both exit error pass dictionary. there solutions out provide this?
for shove,
from shove import shove data = shove('file://tmp') ("a",) in data
it gives me attributeerror: 'tuple' object has no attribute 'rstrip'
. only, if tuple not in data.
from shove import shove data = shove('file://tmp') data[("a",)] = 2 ("a",) in data
would not throw error.
for shelve,
import shelve d = shelve.open('tmp/test.db') d[('a',)] = 2
gives me typeerror: dbm mappings have string indices only
shelve
module python standard library. doc clear : the values (not keys!) in shelf can arbitrary python objects — pickle module can handle ... keys ordinary strings
by construction shelve accept strings keys.
shove still in beta according documentation pypi, , not see evidence supports other string key (the error object has no attribute 'rstrip'
let think not).
if you, stick known shelve
, , wrap key serialisation layer. suggested padraic cunningham, pickle
should job.
here (not extensively tested) possible implementation :
class tuple_dict(collections.mutablemapping): class iterator(collections.iterator): def __init__(self, d): self.it = d.udict.__iter__() def __iter__(self): return self def next(self): return pickle.loads(next(self.it)) def __init__(self, udict): self.udict = udict def __getitem__(self, key): ukey = pickle.dumps(key) return self.udict[ukey] def __setitem__(self, key, value): ukey = pickle.dumps(key) self.udict[ukey] = value def __delitem__(self, key): ukey = pickle.dumps(key) del self.udict[ukey] def keys(self): return [ pickle.loads(key) key in self.udict.keys() ] def __iter__(self): return self.iterator(self) def __len__(self): return len(self.udict) def __contains__(self, key): return pickle.dumps(key) in self.udict def sync(self): self.udict.sync() def close(self): self.udict.close()
you use way :
import shelve underlying_d = shelve.open('tmp/test.db') d = tuple_dict(underlying_d)
d accept tuple keys , stores in underlying shelf.
nb : if later want use different persistence implementation, provided implementation mapping (dict class), reuse tuple_dict
changing close , sync methods (shelve specifice) needed other implentation. in fact apart these 2 methods tuple_dict wraps ordinary dict - , such mapping class ...
Comments
Post a Comment