If conditions for Python dictionaries
So I have a string which is converted into a dictionary called test and
takes the form:
{"a":"1","b":"2","c":"3"}
Now while creating the dictionary, the availablilty of the "c":"3"
key-pair, depends on a some condition; so there are cases when the
dictionary simply reads as:
{"a":"1","b":"2"}
I have an if condition which checks for the existence of the "c" key and
gives some output based on it. The condition is as follows:
if (test["c"]):
print "Hello world!!"
This has no else condition. The problem arises when the 3rd key-value pair
isn't in the dictionary. Running the code gives the following error:
File "test.py", line 14, in test
if test["c"]:
KeyError: 'c'
May I know what I can do to resolve this and what to correct in the code?
No comments:
Post a Comment