I cant print out keys from the replit database

Question:
Hello, I can’t seem to print out the keys from the replit database, I can set keys to the database, delete keys from the database, but im not sure if listing them in a variable even works, because when I list the keys and try to print them, it just shows this ‘KeysView(<Database(db_url=…)>)’, I don’t know if maybe im missing something or this is normal
Repl link:
Delayed - Replit


from replit import db

keys = db.keys()
print(keys)

That seems like it’d be normal, could you try:

from replit import db

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

And see if that output is more what you were expecting? If so, you could always mash that into a list:

from replit import db

dbkeys = []
for key in db.keys():
    dbkeys.extend([key])
print(dbkeys)
1 Like

Thanks! that worked really well, I apperciate the help

1 Like
from replit import db

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

Outputs

KeysView(<Database(db_url=...)>)
<class 'collections.abc.KeysView'>
a
<class 'str'>

This is because keys/db.keys() is not the same thing as the contents of keys/db.keys()

I asked replit ai : why does print(keys) not return the contents of the database but instead KeysView(<Database(db_url=…)>)

(I’m not sure how accurate its responses are so use caution.)

it said :
When you use db.keys() in Replit, it returns a special object called a KeysView. This object represents all the keys in the database, but it doesn’t actually contain the keys themselves. Instead, it acts like a “view” into the database, allowing you to iterate over the keys without having to load them all into memory at once.

I then asked it : someone might expect print(keys) to work like printing an entire list or dictionary but it does not can you clear up the confusion?

it said :
Lists and dictionaries store their elements directly in memory. When you print them, Python shows you the actual contents.

KeysView acts as a “window” into the data, allowing you to see and interact with the elements without having them loaded in memory. It’s a more efficient approach, particularly for larger datasets.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.