Asked • 06/12/19

Check if a given key already exists in a dictionary?

I wanted to test if a key exists in a dictionary before updating the value for the key.I wrote the following code: if 'key1' in dict.keys(): print "blah" else: print "boo"I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?

2 Answers By Expert Tutors

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.