Issue
I have a Python class which takes raw output in nested JSON and assigns commonly used fields to instance variable, below is the code.
self.test_col_1 = [o.get('raw_value1') or None for o in raw_output['raw_col1']]
If raw_value1 key is not found then replace it with None. However, in some cases the raw_col1 key is not present and I get KeyError.
I can use if condition to check if the key is present as below
if raw_output.get('raw_col1'):
self.test_col_1 = [o.get('raw_value1') or None for o in raw_output['raw_col1']]
else:
self.test_col_1 = None
This works fine, however I have many keys and don't want to use the if condition like this for all keys. Is there any other way to obtain the above condition with fewer lines of code.
Solution
You can use raw_output.get("raw_col1", [])
instead of raw_output['raw_col1']
in your code. That will return an empty list instead of a KeyError and will prevent TypeError
from for loop as well.
Answered By - Krishna Khowal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.