I'm making a API call that occasionally does not have certain fields in the response. If I run across one of these responses, my script throws the KeyError as expected, but then breaks out of the for loop completely. Is there any way of getting it to simply skip over the errored output and continue with the loop?
I've considered trying to put all the fields I'm searching for into a list and iterate over that using a continue statement to keep the iteration going when it encounters a missing field, but 1) it seems cumbersome and 2) I've got multiple levels of iterations within the output.
try:
for item in result["results"]:
print(MAJOR_SEP) # Just a line of characters separating the output
print("NPI:", item['number'])
print("First Name:", item['basic']['first_name'])
print("Middle Name:", item['basic']['middle_name'])
print("Last Name:", item['basic']['last_name'])
print("Credential:", item['basic']['credential'])
print(MINOR_SEP)
print("ADDRESSES")
for row in item['addresses']:
print(MINOR_SEP)
print(row['address_purpose'])
print("Address (Line 1):", row['address_1'])
print("Address (Line 2):", row['address_2'])
print("City:", row['city'])
print("State:", row['state'])
print("ZIP:", row['postal_code'])
print("")
print("Phone:", row['telephone_number'])
print("Fax:", row['fax_number'])
print(MINOR_SEP)
print("LICENSES")
for row in item['taxonomies']:
print(MINOR_SEP)
print("State License: {} - {}, {}".format(row['state'],row['license'],row['desc']))
print(MINOR_SEP)
print("OTHER IDENTIFIERS")
for row in item['identifiers']:
print(MINOR_SEP)
print("Other Identifier: {} - {}, {}".format(row['state'],row['identifier'],row['desc']))
print(MAJOR_SEP)
except KeyError as e:
print("{} is not defined.".format(e))