sqldict - You have a dict with unlimited capacity, what do you do? (it can store arbitrary objects too)

Krister Hedfors krister.hedfors at gmail.com
Thu Apr 15 08:21:23 EDT 2010


sqldict - dict with sqlalchemy database-agnostic back-end

You can now create a dict out of arbitrary key/value columns of
any existing database table, in addition to ordinary dedicated
strict or auto-pickling sqldicts.

Basic use:
  $ easy_install sqldict
  $ easy_install sqlalchemy

  >>> from sqldict import sqldict
  >>> from sqlalchemy import *
  >>> #d0 = sqldict("mysql://user:pass@dbhost/dbname", "table0", create=1)
  >>> engine = create_engine("sqlite://")
  >>> d1 = sqldict(engine, "table1", create=1)
  >>> d2 = sqldict(engine, "table2", create=1, valtype=Integer)
  >>> contents = {"asd":123}
  >>> d1.update(contents)
  >>> d2.update(contents)
  >>> assert d1["asd"] == "123"
  >>> assert d2["asd"] == 123

Make dict from existing database table:

  >>> _ = engine.execute("create table asd (i integer, s varchar(50))")
  >>> _ = engine.execute("insert into asd values (42, 'gubbe')")
  >>> d3 = sqldict(engine, "asd", keycol="s", valcol="i")
  >>> d4 = sqldict(engine, "asd", keycol="i", valcol="s")
  >>> assert d3["gubbe"] == 42
  >>> assert d4[42] == "gubbe"

Key-val serializing and only val serializing sqldicts;
a's key column type is String, b's key column type is Integer.
The obvious use case for b is HUGE dicts where only integer
indexes are allowed:

  >>> a = sqldict(engine, "serty1", create=1, serialize=1)
  >>> b = sqldict(engine, "serty2", create=1, serialize=1, keytype=Integer)
  >>>
  >>> a[1] = (2,3)
  >>> assert a[1] == (2,3)
  >>> b[4] = (5,6)
  >>> assert b[4] == (5,6)

Have fun!
/Krister Hedfors



More information about the Python-list mailing list