I’m having trouble printing database values

Asked

Viewed 34 times

0

I am trying to print the 'ok' on the screen when it finds the value '3' inside one of the Keys of the database.

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

0


By the type of error it seems that the user list you are trying to update is not initialized in the corresponding keys.

However, starting from the premise that the user list has been initialized and updated correctly, try the following loop.

    for i in user:
     if (i=='3'):
      print('ok')
  • The problem is that this way does not appear the 'ok' because it will look between the values from 0 to 2 (which are the keys). I want the program to look for the values that are inside the keys

  • I believe not Thomas Caio. See example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.