Creating a dictionary from a dictionary using a tuple Python
<p>given a dictionary with N keys and a tuple of K keys, K&lt;=N is there a pythonic way to get a dictionary with only the K keys?</p>

<p>ex. </p>

<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}

tuple = ('key2', 'keyM')

newdict = myFunc(orig_dict, tuple)

print newdict
</code></pre>

<p>Output:</p>

<pre><code>'key2':'value2', 'keyM':'valueM'
</code></pre>

<p>Just use a comprehension:</p>

<pre><code>tple = ('key2', 'keyM')
{k: orig_dict[k] for k in tple}
</code></pre>

<p>Or if you prefer functional:</p>

<pre><code>from operator import itemgetter

dict(zip(tple, itemgetter(*tple)(orig_dict)))
</code></pre>

<p>What is more <em>pythonic</em> is debatable, what is definitely not pythonic is using <em>tuple</em> as a variable name.</p>

<p>If some keys may not exist you can get the <a href="https://en.wikipedia.org/wiki/Intersection_(set_theory)" rel="nofollow"><em>intersection</em></a> with <a href="https://docs.python.org/2/library/stdtypes.html#dict.viewkeys" rel="nofollow"><em>viewkeys</em></a>:</p>

<pre><code>dict(zip(tuple, itemgetter(*orig_dict.viewkeys() &amp; tple)(orig_dict)))

{k : orig_dict[k] for k in orig_dict.viewkeys() &amp; tple}
</code></pre>

<p>For <code>python3</code> just use <code>.keys()</code> which  returns a <em>dict_view</em> object as opposed to a list in python2.</p>

<p>If you wanted to give a default value of <em>None</em> for missing keys, you could also use <em>map</em> with <em>dict.get</em> so missing keys would have their value set to None.</p>

<pre><code>dict(zip(tuple, map(orig_dict.get, tuple)
</code></pre>

python dictionary tuples