how to repeat / expand expressions in python
<p>What is the most pythonic way to repeat an expression in Python. </p>

<p><strong>Context :</strong> A function is getting passed a dictionary (with possibly 20 elements) and I need to extract and use values from this dictionary <strong>if they exist</strong>. Something like this :</p>

<pre><code>x = dict_name['key1'] if dict_name['key1'] else ''
</code></pre>

<p>Now, instead of writing this logic 20 times for all 20 different keys, I would like to define this expression at one place and then use it repeatedly. It will be easier to maintain in future. In "C/C++" programming languages, it makes a good case of <code>#define</code> or <code>inline</code> functions. What would be Pythonic way to do this in Python?</p>

<p>As you would have guessed, I am novice in Python. So I appreciate your help on this or pointers to constructs for this in Python.</p>

<p>Whether there is an "equivalent" to <code>inline</code> in Python depends on who you ask, and what you check.</p>

<p>For no equivalent, e.g.: <a href="http://stackoverflow.com/a/6442497/2707864">http://stackoverflow.com/a/6442497/2707864</a></p>

<p>For equivalent, e.g.: <a href="https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html" rel="nofollow">https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html</a></p>

<p>From a practical point of view, <code>lambda</code> would do the trick (<code>dict.get</code> replaces your ternary conditional operator)</p>

<pre><code>dict_get = lambda key : dict_name.get(key, '')
</code></pre>

<p>Or you can always define a one-line function.</p>

<pre><code>def dict_get( key ) : dict_name.get( key, '' )
</code></pre>

<p>Pythonicity is quite often (always?) subjective.</p>

python inline