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>Use a dictionary comprehension</p>

<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
keys = ('key2', 'keyM')

&gt;&gt;&gt; {k:orig_dict[k] for k in keys if k in orig_dict}
{'key2': 'value2'}
</code></pre>

<p>This will be more efficient than iterating over the dictionary's keys and checking whether the key exists in the tuple because it is an O(1) operation to lookup a dict vs O(n) to search in a tuple.</p>

<p>Alternatively you can use a set to get the common keys and combine that with a dict comprehension:</p>

<pre><code>&gt;&gt;&gt; {k:orig_dict[k] for k in set(keys).intersection(orig_dict)}
{'key2': 'value2'}
</code></pre>

python dictionary tuples