Ask coding questions

← Back to all posts
(Python) Is there a way to check if a database key exists?
leosefcik (1)

Hello, I’d like to know if there’s a way to check if a repl.it database key exists or not. Something like:

x = input()
if db[x] exists:
db[x] = db[x]+1
else:
db[x] = 0

Answered by Smart0ne (743) [earned 5 cycles]
View Answer
Comments
hotnewtop
Smart0ne (743)
x = input()
db_keys = db.keys()
if x in db_keys:
  print(f"{x} is a key")
else:
  print(f"{x} is not a key")

"db.keys()" returns a KeysView object that contains all the keys in the database.

badst (240)
x = input()
if x in db.keys():
    db[x]+=1
else:
    db[x]=0