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.
You can probably try to add it by using
try and if it returns an error then use
except to create the key and add the value. For example:
def add_to_db(): try: #add a value to the key except: #Create a key and adds the value
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.
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"