Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix default values from a dictionary Pythonically?

Tags:

python

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

like image 647
Jesvin Jose Avatar asked Oct 07 '11 14:10

Jesvin Jose


People also ask

How do I change the default value in a dictionary?

Python Dictionary setdefault() Method Syntax: Parameters: It takes two parameters: key – Key to be searched in the dictionary. default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.

How do you set a value in a dictionary in a way that doesn't override existing values?

By using the setdefault() method, you can add items with new values only for new keys without changing the values for existing keys. This is useful when you don't want to change an existing item. This article describes the following contents.

What is the default value of dictionary in Python?

default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError .

How do you grab a value from a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.


1 Answers

Use the dict.update method on a copy of the defaults:

defaults = dict(a=1, b=2, c=3)

result = dict(defaults)  # Copy the defaults
result.update(request)  # Update with your values

This allows you to keep defaults as a class attribute or module global variable, which you probably want to do.

You can also combine the last two lines into:

result = dict(defaults, **request)

For another solution, see Kevin's answer.

like image 178
Petr Viktorin Avatar answered Sep 18 '22 14:09

Petr Viktorin