Home > Mobile >  How can I pass a dictionary name into a function and handle KeyError inside the function?
How can I pass a dictionary name into a function and handle KeyError inside the function?

Time:10-21

I have a function:

def print_boardrow(row, content, alt_content):
    for i in row:
        try:
            print(content, end="")
        except KeyError:
            print(alt_content, end="")

And I want to call it like this:

print_boardrow(row, slot[i[0]][0], "    ")

But this wouldnt work as 'i' is defined inside the function and KeyError would be raised before the function is executed. How can I make it work? (row is a list and slot is a dictionary)

CodePudding user response:

How about restructuring the code slightly?

def print_boardrow(row, key, alt_content):
  print(row.get(key, alt_content), end='')

print_board_row(row, i[0], '    ')

Not sure what the loop inside the original function is achieving so left it out here. The general idea is the use of get() which removes the possibility of KeyError because, if the key is not found, the alternative (default) will be returned

  • Related