Python if/elseif construction as dictionary
Question: In Python I use regularly the following construct:

    
    
    x = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    y = x[v] if v in x.keys() else None
    

where v is normally one of the dictionary values, and y gets the value of the
dictionary if the key exists, otherwise None.

I was wondering if this is a desired construct or if it can be enhanced?

x[v] can be values as above, but I also use a similar construct to call a
function depending on the value of v, like:

    
    
    {'a': self.f1, 'b': self.f2, 'c': self.f3, 'd': self.f4}[v]()
    


Answer: Normally you'd use
[`dict.get()`](http://docs.python.org/2/library/stdtypes.html#dict.get):

    
    
    y = x.get(v)
    

`.get()` takes a default parameter to return if `v` is not present in the
dictionary, but if you omit it `None` is returned.

Even if you were to use an explicit key test, you don't need to use `.keys()`:

    
    
    y = x[v] if v in x else None
    

Interestingly enough, the conditional expression option is slightly faster:

    
    
    >>> [x.get(v) for v in 'acxz']  # demonstration of the test; two hits, two misses
    [1, 3, None, None]
    >>> timeit.timeit("for v in 'acxz': x.get(v)", 'from __main__ import x')
    0.8269917964935303
    >>> timeit.timeit("for v in 'acxz': x[v] if v in x else None", 'from __main__ import x')
    0.67330002784729
    

until you avoid the attribute lookup for `.get()`:

    
    
    >>> timeit.timeit("for v in 'acxz': get(v)", 'from __main__ import x; get = x.get')
    0.6585619449615479
    

so if speed matters, store a reference to the `.get()` method (note the `get =
x.get` assignment).

