Ask coding questions

← Back to all posts
Python- How to see if a db key exists?
PikachuB2005 (7)

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.

Answered by IMayBeMe (346) [earned 5 cycles]
View Answer
IMayBeMe (346)

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():
    #add a value to the key
    #Create a key and adds the value
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:

  # 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
#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"