If you have nested dictionaries, you must be careful. Most python objects are not sorted (and you can stuff any object as a value in a dict ). Even worse, even fewer python objects can be converted to strings and stored in SQL.
However, if you use klepto , serialization and storage in the database are pretty transparent and work for most python objects.
Let's build some typical python objects in a dict (or dicts):
>>> class Foo(object): ... def bar(self, x): ... return self.y + x ... y = 1 ... >>> d1 = {'a': min, 'b': lambda x:x**2, 'c': [1,2,3], 'd': Foo()} >>> f = Foo(); fy = 100 >>> d2 = {'a': max, 'b': lambda x:x**3, 'c': [2,1,3], 'd': f}
Now create a nested dict and a dump in the MYSQL archive.
>>> import klepto >>> a = klepto.archives.sql_archive('mysql://user: pass@localhost /foo', dict={'d1':d1, 'd2':d2}) >>> a.dump()
Now we delete our interface in the archive ... and create a new one. load loads all objects into memory.
>>> del a >>> b = klepto.archives.sql_archive('mysql://user: pass@localhost /foo') >>> b.load()
Now we get access to the objects in copies in memory.
>>> b['d1'] {'a': <built-in function min>, 'c': [1, 2, 3], 'b': <function <lambda> at 0x1037ccd70>, 'd': <__main__.Foo object at 0x103938ed0>} >>> b['d1']['b'](b['d1']['d'].bar(1)) 4 >>> b['d2']['b'](b['d2']['d'].bar(1)) 1030301 >>>
We exit python ... and then start a new session. This time we decided to use cached=False , so we will interact directly with the database.
dude@hilbert >$ python Python 2.7.10 (default, May 25 2015, 13:16:30) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import klepto >>> b = klepto.archives.sql_archive('mysql://user: pass@localhost /foo', cached=False) >>> b['d2']['b'](b['d2']['d'].bar(1)) 1030301 >>> b['d1']['b'](b['d1']['d'].bar(1)) 4 >>>
klepto uses sqlalchemy , so it works with several database backends ... and, in addition, provides the same dict based dict for storage on disk (in a file or directory).