How Do You Write Python Code to Test if a Dictionary Exists?

Problem scenario
You want to test if a dictionary exists or not. You know its name if/when it exists. What do you do?

Solution

# Suggested usage: 1) run it is as it is.  
# 2) uncomment out the dictionary_name1 definition stanza. 
# Then run this program again.

#dictionary_name1 = "good_dict"

if 'dictionary_name1' in locals():
  print("IT IS IN LOCALS")
else:
  print("IT IS NOT IN LOCALS")

if 'dictionary_name1' in globals():
  print("IT IS IN GLOBALS")
else:
  print("IT IS NOT IN GLOBALS")

Leave a comment

Your email address will not be published. Required fields are marked *