Jochen Ritzel's answer is the right way to do this 99.9999% of the time:
variable = d.get("the key", "something")
As he notes, this does not allow you to shortly complete the evaluation of the default value. You usually don't care. The default value is "something" course you do not. This only matters if the default is either dangerous or a very expensive creation.
Only in this case you can and should use your idea. Except that you want in instead of has_key (because it is more readable and faster, not obsolete):
variable = d["the key"] if "the key" in d else expensiveComputation()
However, it is probably worth using an if instead of a triple expression, because the fact that you are avoiding expensiveComputation is important and you want it to be more visible:
if "the_key" in d: variable = d["the key"] else: variable = expensiveComputation()
If you expect the default case to be rare, this is better:
try: variable = d["the key"] except KeyError: variable = expensiveComputation()
If for some reason you need to avoid double key lookups, and you also cannot handle exceptions, and you need to disable the default immediately:
sentinel = object() variable = d.get(sentinel) if variable == sentinel: variable = expensiveComputation()
And yes, you could wrap it all up with a function so that it is single-line, but you almost certainly don't want to hide the fact that you are doing three rare things at once.
Or, of course, you could do this:
d = collections.defaultdict(expensiveComputation)
Then just:
variable = d["the key"]
This has a side effect from setting d["the key"] to expensiveComputation() before returning it to you, so a later call to d["the key"] will return the same value. If that sounds appropriate, this is the best answer; if you will never use the same key twice, or these things are huge and wasteful to get around, etc., this is a bad idea.
Or, alternatively, you can override the dict.__missing__ instead of using defaultdict :
class MyDict(dict): def __missing__(self, key): return expensiveComputation()
Then, again, this is simple:
variable = d["the key"]
This approach is suitable when you want to generate a value separately each time, rather than saving it later.