Python- How to see if a db key exists?
I want to make something so that if I want to add something to a key that doesn't exist, it will create the key, then add it. But I can't find a way to test whether it already exists or not.
Coder100 (17045)
the db can be treated like a dict. You can check if a dict contains a key like this:
if key in db:
where key is the key.
A more idiomatic approach is:
try:
db[key]
except:
# key doesn't exist, do something
where key, of course, is the key.
Bookie0 (5976)
db['hello'] = 'yes'
if 'hello' in db: # checks if the key 'hello' is in the dict
# something
else: # if not, adds it.
db['hello'] = 'something'
19ecal (230)
Try something like this
from replit import db
#create a list of keys
keys=list(db.keys())
#set key to "a key"
key="a key"
#if the key is already in the list
if key in keys:
print("That already exists")
#if the key isn't in the list
elif key not in keys:
#set value at the key to whatever you want
db[key]="whatever you want"
You can probably try to add it by using
try
and if it returns an error then useexcept
to create the key and add the value. For example: