-3

When I try to loop trough items in json and some of them doesn't contain element which I am evoking I am getting Key Error.

for i in range(200000): #(amount of lines in file):
 data["tasks"][i]["Assignments"] = [data["tasks"][i]["Assignments"][0]]
    
KeyError: 'Assignments'

How can I avoid this error?

LuiTe
  • 51
  • 7

1 Answers1

1

Just use try/except as mentioned in the comments

for i in range(200000): #(amount of lines in file):
    try:
        data["tasks"][i]["Assignments"] = [data["tasks"][i]["Assignments"][0]]
    # if KeyError occurs, just skip the line
    except KeyError:
        continue
f44g5
  • 31
  • 3