I am parsing JSON requests using the JSON library which parses into python dictionary. As the requests are user-generated, I need to fix default values for parameters that have not been supplied. Other languages have stuff like ternary operators which make sense for repetitive applications. But the code below needs 4 lines per parameter.
if "search_term" in request.keys():
search_term=request['search_term']
else:
search_term=""
if "start" in request.keys():
start=request['start']
else:
start=0
if "rows" in request.keys():
rows=request['rows']
else:
rows=1000000
Is there a Pythonic way to reduce the lines of code or make it more readable?
Edit: Both the (top) answers are equally useful. I used both in different circumstances
Use the
dict.updatemethod on a copy of the defaults:This allows you to keep
defaultsas a class attribute or module global variable, which you probably want to do.You can also combine the last two lines into:
For another solution, see Kevin’s answer.