Using the dbm module in Python 3

I am studying database files and the dbm module in Python 3.1.3, and I am having problems using some methods from the anydbm module in Python 2.

The key method works great,

import dbm

db = dbm.open('dbm', 'c')
db['modest'] = 'mouse'
db['dream'] = 'theater'

for key in db.keys():
    print(key)

gives:

b'modest'
b'dream'

but the elements and meanings

for k,v in db.items():
    print(k, v)

for val in db.values():
    print(val)

raises an AttributeError object: '_dbm.dbm' has no attributes 'items'.

In addition, these are:

for key in db:
    print(key)

gets a TypeError object: '_dbm.dbm' is not iterable.

These methods just don't work in the dbm module in Python 3? If true, is there anything else I could use instead?

+3
source share
2 answers

, , . dbm Python 3 ndbm, dbm Python 2. , .

, anydbm Python 2 dumbdbm, , .

, shelve, Python 2, 3, ( pickleable ).

+2

- /. , . :

values = [db[key] for key in db.keys()]

. , / , . , SQLite ?

, dumbdbm dbm.dumb Python 3.

>>> import dbm
>>> db = dbm.dumb.open('dbm', 'c')
>>> 
>>> db['modest'] = 'mouse'
>>> db['dream'] = 'theater'
>>> for key in db.keys():
...     print(key)
... 
b'modest'
b'dream'
>>> for k,v in db.items():
...     print(k, v)
... 
b'modest' b'mouse'
b'dream' b'theater'
>>> for val in db.values():
...     print(val)
... 
b'mouse'
b'theater'
+1

All Articles