Dictionaries and default values
Assuming connectionDetails
is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this?
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
Solution 1:
Like this:
host = connectionDetails.get('host', someDefaultValue)
Solution 2:
You can also use the defaultdict
like so:
from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"
You can pass any ordinary function instead of lambda:
from collections import defaultdict
def a():
return 4
b = defaultdict(a, key="some_value")
b['absent'] => 4
b['key'] => "some_value"