Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a value in a dict only if the value is not already set

What is the most pythonic way to set a value in a dict if the value is not already set?

At the moment my code uses if statements:

if "timeout" not in connection_settings:
    connection_settings["timeout"] = compute_default_timeout(connection_settings)

dict.get(key,default) is appropriate for code consuming a dict, not for code that is preparing a dict to be passed to another function. You can use it to set something but its no prettier imo:

connection_settings["timeout"] = connection_settings.get("timeout", \
    compute_default_timeout(connection_settings))

would evaluate the compute function even if the dict contained the key; bug.

Defaultdict is when default values are the same.

Of course there are many times you set primative values that don't need computing as defaults, and they can of course use dict.setdefault. But how about the more complex cases?

like image 855
Will Avatar asked Apr 12 '13 07:04

Will


1 Answers

dict.setdefault will precisely "set a value in a dict only if the value is not already set".

You still need to compute the value to pass it in as the parameter:

connection_settings.setdefault("timeout", compute_default_timeout(connection_settings))
like image 151
Janne Karila Avatar answered Oct 24 '22 13:10

Janne Karila