PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How can I pass a dictionary name into a function and handle KeyError inside the function?

 November 14, 2022     error-handling, function, python     No comments   

Issue

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)


Solution

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



Answered By - Cobra
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing