REMEMBER PYTHON

MINTE9
2REMEMBER




DB MODULE

p252 ! Many databases are like dictionaries (map keys to values). The difference is that the database is on disk.
 CodeCopy
import dbm

db = dbm.open('images', 'c')
db['myimage.jpg'] = '/images/myimage.jpg'
db['myimage.png'] = '/images/myimage.png'

print(db['myimage.jpg']) 

# b'/images/myimage.jpg'
# the result is a bytes object (it begins with b)

db.close()
... 8 lines
˄˄˄
p253 You can use dictionaries methods to loop through items.
 CodeCopy
import dbm
db = dbm.open('images_db')

for key in db.keys():
    print(key, db[key])

# b'myimage.png' b'/images/myimage.png'
# b'myimage.jpg' b'/images/myimage.jpg'

db.close()
... 7 lines
˄˄˄
Pickling    (2/2)

Pickling

! A limitation of db is that it works only with strings or bytes. With pickle module you can store any type.
 CodeCopy
import dbm
import pickle

# write
db = dbm.open('images_db', 'w')
t = [1, 2, 3]
s = pickle.dumps(t) # b'\x80\x03]q\x00(K\x01K\x02K\x03e.'
db['mylist'] = s
db.close()

# read
db = dbm.open('images_db')
b = db['mylist']
s = pickle.loads(b)
print(s) # [1, 2, 3]
db.close()
... 14 lines
˄˄˄
Pickling and reversing has the same effect as copying the object.
 CodeCopy
import pickle

t1 = (1, 2, 3)
s = pickle.dumps(t1)
t2 = pickle.loads(s)
print(t2) # (1, 2, 3)

print(t1 == t2) # True
print(t1 is t2) # False 
... 7 lines
˄˄˄

Shelve

In a 'shelf' db the values can be any objects that pickle can handle.
 CodeCopy
import shelve

t = (1, 2, 3)
db = shelve.open("images_db", 'w')
db['my_tuple'] = t
db.close()

db = shelve.open("images_db", 'w')
assert db['my_tuple'] == (1, 2, 3) # pass
db.close()
... 8 lines
˄˄˄

Questions    
No. 23   Pipes
CARD
22
32

        A B C D E F
🔔
1/2