DEV Community

petercour
petercour

Posted on

Python Dictionary-like objects into database

Dictionaries are key,value pair groups. But by default that's stored in memory. That works fine, until you run out of memory.

You can create dictionary like objects, data is immediately stored into a SQLite database.

How is this different from a normal dictionary?

  • data is stored on the disk, not memory
  • creates sqlite database file and stores data there
  • dictionary can be explored with a tool like sqlitebrowser

Usage like this:

#!/usr/bin/python3
from dbdict import dbdict

d = dbdict("dummy")
d["foo"] = "bar"
d["key"] = "value"
d["pi"] = 3.14159
print(d["key"])

d["foo"] = "foo foo"
print(d["foo"])
print(d.keys())

for key in d.keys():
    print("* d[" + str(key) + "] = " + str(d[key]))

Then you can explore with any sqlite browser program.

The class does all the querying, inserting, table creation and so on.

So if instead you want to use another database than SQLite, you can just change the module (sqlite) and change the queries for that database system. In theory that should work with any database system once changed.

Download class: https://github.com/petercour/sqlite-dict-for-python/blob/master/dbdict.py

Learn Python:

Oldest comments (0)