Ternary operation in the dictionary

Is there a way to do a triple operation on the speaker where the has_key () test without clicking on a key error? i.e.

variable = dict["the_key"] if dict.has_key("the_key") else "something" 

(this clearly means a key error)

otherwise, what is the most pythonic way to assign a bunch of dict-based variable values ​​that may or may not have corresponding keys? Repeating:

 if dict.has_key('key'): value = dict['key'] else: value = "value" 

ad nauseum seems very inelegant.

+4
source share
5 answers

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.

+5
source

It:

 mydict.get(key, default_value) 

Not 100%, just as default_value is evaluated immediately, and the else part is evaluated only when the condition is met.

+10
source

Use the .get () method - it will return None if the key does not exist, or you can set your own by default:

http://docs.python.org/2/library/stdtypes.html#dict.get

 value = mydict.get("key", "default") 
+3
source

variable = d['the_key'] if 'the_key' in d else 'something'

+1
source
 value = 'value' if 'key' in dict: value = dict['key'] 

or define a default value

dict.get ('key', 'value')

0
source

All Articles