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
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
For multiple different defaults try this:
You can use a lamba function for this as a one-liner. Make a new object
connectionDetails2
which is accessed like a function...Now use
instead of
which returns the dictionary value if
k
is in the keys, otherwise it returns"DEFAULT"
There is a method in python dictionaries to do this:
dict.setdefault
However this method sets the value of
connectionDetails['host']
tosomeDefaultValue
if keyhost
is not already defined, unlike what the question asked.Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both
.get()
and theif
/else
way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with the last case where there is two lookups).Like this:
You can also use the
defaultdict
like so:You can pass any ordinary function instead of lambda: