Pickle DB - A fantastic key-value store

in #python7 years ago

0-Intro_pickles_Brand X Pictures-Thinkstock.jpg

Fantastic Pickles!



Recently I've been using PickleDB for storing simple key-value data and I really like it. It's so simple and easy to use it's unreal. Here's the basic setup.

import pickledb

db = pickledb.load('data.db', False)

db.set('key', 'value')
db.dump()

print(db.get('key'))



Simple right? Let's have a mess around with it and see what it can do. We'll dump some test data in it first.

import pickledb

db = pickledb.load('data.db', False)

things = ['one', 'two', 'three', 'four', 'five']

for i, thing in enumerate(things, start=1):
    db.set(thing, i)

db.dump()



You should now see this in data.db

{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}



Better we read it using python actually..

for x in db.getall():
    print(x, db.get(x))



Which should print out this.

one 1
two 2
three 3
four 4
five 5



Increment the values by 1. No problem.

db = pickledb.load('data.db', False)

for x in db.getall():
    print(x, db.get(x))
    db.set(x, db.get(x) + 1)

db.dump()



Notice the db.dump() after we add entries to the database. This does exactly what you'd think... dumps the gathered/changed data to the database. You have the option to set live changes or not and do away with db.dump() by changing this line to True.

db = pickledb.load('data.db', False)



Add an entry if it does not exist in the database.

if not db.exists('six'):
    db.set('six', 6)



As you can see, this is child's play. There are plenty other handy commands to use but I'll not go through them all. You can read all about them here.

Thanks for reading. x

Resources

Coin Marketplace

STEEM 0.05
TRX 0.33
JST 0.080
BTC 63398.51
ETH 1702.04
USDT 1.00
SBD 0.41