I have a dictionary that has three different kinds of key-value pairs in it. The values are one of the three shapes: A dictionary, null, or an integer, e.g.:
dic = {"range" : {"val": 1, "size": 2}, "length" : {"val": 5, "radius": 1}, "power": null, "current": 5} I am using a try-except block, with the dictionary value as default, and want to catch the TypeError for null and integer separately. For value null, it gives "TypeError: 'NoneType' object is not subscriptable" and for an integer, it gives "TypeError: 'int' object is not subscriptable". How do I catch these errors in different exceptions? I am looping through the keys of interest in the dictionary and an example of what I am currently doing is below, however it catches both errors as they are both TypeError:
for kw in list_of_keys: try: val_test = dic[kw]['val'] except TypeError: val_test = dic[kw] I would like to catch errors similar to the following:
for kw in list_of_keys: try: val_test = dic[kw]['val'] except TypeError: 'int' object is not subscriptable: val_test = dic[kw] except TypeError: 'NoneType' object is not subscriptable: val_test = "Not implemented / Not given yet" Thank you for your help!
dic[kw]before trying to do anything with it.None, notnull, right?TypeErrorand then check what the argument says, though