Python KeyError if logic or try logic -
i'm trying loop through json data export csv , going until portion of data need field values these fields not exist beneath "tags".
i'm getting error of:
for alarm in tag["alarmst"]: keyerror: 'alarmst' i believe built-in exceptions reading means key/field not exist.
i read in errors , exceptions can put logic in try statement say, if key not exist, don't give me error , else or move onto next set of records beneath "tag" "alarmst" , dump (and other fields specified) file.
i'm having trouble figuring out how tell logic stop giving me error , use csv_file.writerow() function field values if "alarmst" exist.
since working 1 file , processes before python process runs "devs" , "tags" own csv files, cannot parse data , cut down on loops within other loops.
i'm not sure if issue if tag["alarmst"] in tag: due there being many loops within others, or if need use try statement somehow instead, or if i'm not doing else correctly since i'm new python @ level of coding seems work need far.
i'm running on windows 10 os if makes difference assume doesn't.
starting code:
import json import csv open('c:\\folder\\dev\\tagalarms.txt',"r") file: data = json.load(file) open('c:\\folder\\dev\\tagalarms.csv',"w",newline='') file: csv_file = csv.writer(file) dev in data["devs"]: tag in dev["tags"]: alarm in tag["alarmst"]: csv_file.writerow(alarm['datestatus'],[alarm['datestart'], alarm['status'], alarm['type']]) if code:
import json import csv open('c:\\folder\\dev\\tagalarms.txt',"r") file: data = json.load(file) open('c:\\folder\\dev\\tagalarms.csv',"w",newline='') file: csv_file = csv.writer(file) dev in data["devs"]: tag in dev["tags"]: alarm in tag["alarmst"]: if tag["alarmst"] in tag: csv_file.writerow(alarm['datestatus'],[alarm['datestart'], alarm['status'], alarm['type']])
tag["alarmst"] throws error. means getting value tag associated key "alarmst" , there no such key fails. if tag["alarmst"] in tag throw same error, , won't reach point if it's below for alarm in tag["alarmst"]:. want is:
if "alarmst" in tag: alarm in tag["alarmst"]: but nicer is:
for alarm in tag.get("alarmst", []): get similar usual square bracket access second argument default if key not found. if "alarmst" not in dictionary be:
for alarm in []: which empty loop won't run @ all.
Comments
Post a Comment