简体   繁体   English

使用 Python 中的 dbm 模块 3

[英]Using the dbm module in Python 3

I'm learning about database files and the dbm module in Python 3.1.3, and am having trouble using some of the methods from the anydbm module in Python 2.我正在学习 Python 3.1.3 中的数据库文件和 dbm 模块,并且在使用 Python 2 中的 anydbm 模块中的一些方法时遇到了问题。

The keys method works fine,键方法工作正常,

import dbm

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

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

yields:产量:

b'modest'
b'dream'

but items and values,但是项目和价值观,

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

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

bring up an AttributeError: '_dbm.dbm' object has no attribute 'items'.出现 AttributeError: '_dbm.dbm' object has no attribute 'items'。

Also, this:另外,这个:

for key in db:
    print(key)

gets a TypeError: '_dbm.dbm' object is not iterable.得到一个 TypeError: '_dbm.dbm' object is not iterable。

Do these methods just not work in the dbm module in Python 3?这些方法在 Python 3 的 dbm 模块中不起作用吗? If that's true, is there anything else that I could use instead?如果这是真的,我还有什么可以代替的吗?

I think this depends which implementation it chooses to use.我认为这取决于它选择使用哪种实现。 On my system, dbm in Python 3 chooses to use ndbm, which is equivalent to the dbm module in Python 2. When I use that module explicitly, I see the same limitations.在我的系统上,Python 3 中的 dbm 选择使用 ndbm,这相当于 Python 2 中的dbm模块。当我明确使用该模块时,我看到了相同的限制。

It appears anydbm in Python 2 chooses dumbdbm, which is slower, but does support the full dictionary interface. Python 2 中出现anydbm 选择dumbdbm,速度较慢,但确实支持全字典接口。

You might want to look at the shelve module, in both Python 2 and 3, which adds another layer over these interfaces (allowing you to store any pickleable object).您可能想查看 Python 2 和 3 中的shelve模块,它在这些接口上添加了另一层(允许您存储任何可腌制对象)。

The purpose of these sort of simple databases is to act as key/value stores.这些简单数据库的目的是充当键/值存储。 It you want all the values, you have to iterate over all the keys.如果您想要所有值,则必须遍历所有键。 Ie: IE:

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

That will not be fast.那不会很快。 It may me that this sort of key/value store isn't really what you need.我可能认为这种键/值存储并不是您真正需要的。 Perhaps SQLite would be better?也许 SQLite 会更好?

That said, you can access dumbdbm under the name of dbm.dumb in Python 3.也就是说,您可以在 Python 3 中以 dbm.dumb 的名称访问dumbdbm。

>>> 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM