+3 votes
2 views
in Python by (3.5k points)
edited by

How can I check if a key exists in a directory in Python, before updating the value of the key. I tried this code:

    if 'key1' in dict.keys():
      print "Y"
    else:
      print "N"

 Is there a better way to do this?

2 Answers

0 votes
by (2k points)
edited by

Just don't call keys, for instance try this:

if 'key1' in dict:
  print "Y"
else:
  print "N"

Alternatively You can also use,  in operator to test the existence of a key in a dict. Ex.

r = {'q': 2, 'w': 3}
'q' in r # <== evaluates to True
'e' in r # <== evaluates to False

It's the fastest way to perform the task.

Don't feel shy to ask your doubt in comment. Happy Learning.

0 votes
by (107k points)

You don't have to call keys:

if 'key1' in dict:

  print "blah"

else:

  print "boo"

You can use the following video tutorials to clear all your doubts:-

Related questions

+1 vote
1 answer
+1 vote
1 answer
+1 vote
2 answers
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.8k points)
+1 vote
4 answers
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...