Suppose I am parsing a fixed-width file:
file_format = {'year' : (0, 3, int), 'price' : (4, 10, float)}
for lineno, line in enumerate(input_file):
try:
fields = {k : v[2](line[v[0]:v[1]]) for k, v in file_format.items()}
except ValueError:
print("cannot parse line {}".format(lineno))
I would like to add to the exception printout the information about which particular field couldn’t be parsed. Is there any way I could retrieve k and v values without replacing the dict comprehension with a loop?
You could shift the problematic part into a function