Python DBM KeyError

时间:2017-10-24 17:21:22

标签: python keyerror dbm

当我在for

中找到一个键值时,如何打印'ok'
>>> with dbm.open('data1.db','r') as user:
    user['0'] = '1'
    user['1'] = '2'
    user['2'] = '3'
    for i in user:
        if '3' in user[str(i)]:
            print('ok')


Traceback (most recent call last):
  File "<pyshell#146>", line 3, in <module>
    if '3' in user[str(i)]:
  File "C:\Users\ThomasNote\AppData\Local\Programs\Python\Python36-32\lib\dbm\dumb.py", line 148, in __getitem__
    pos, siz = self._index[key]     # may raise KeyError
KeyError: b"b'0'"

在这里,我可以打印键值和键中包含的数据,但我只想搜索包含键值的单词。

with dbm.open('data1.db','r') as user:
    for i in user:
        print(i.decode(), user[i].decode())

>>> 0 1
>>> 1 2
>>> 2 3 

1 个答案:

答案 0 :(得分:0)

如果要检查是否存在特定值,只需遍历键:

import dbm
db = dbm.open('/tmp/example', 'n')
db['key'] = 'value'
db['name'] = 'marc'
db['1'] = '3'
values = [db[key] for key in db.keys()]

print values
['3', 'value', 'marc']

if '3' in values: print 'ok'
ok

检查密钥是否退出:

if db.has_key('name'): print 'ok'
ok