Way to get specific keys from dictionary
<p>I am looking for a way to get specific keys from a dictionary. </p>

<p>In the example below, I am trying to <code>get all keys except 'inside'</code></p>

<pre><code>&gt;&gt;&gt; d
{'shape': 'unchanged', 'fill': 'unchanged', 'angle': 'unchanged', 'inside': 'a-&gt;e', 'size': 'unchanged'}
&gt;&gt;&gt; d_keys = list(set(d.keys()) - set(["inside"]) )
&gt;&gt;&gt; d_keys
['shape', 'fill', 'angle', 'size']
&gt;&gt;&gt; for key in d_keys:
...     print "key: %s, value: %s" % (key, d[key])
...
key: shape, value: unchanged
key: fill, value: unchanged
key: angle, value: unchanged
key: size, value: unchanged
</code></pre>

<p>Is there a better way to do this than above?</p>

<p>In python 3.X most of dictionary attributes like <code>keys</code>, return a view object which is a set-like object, so you don't need to convert it to set again:</p>

<pre><code>&gt;&gt;&gt; d_keys = d.keys() - {"inside",}
&gt;&gt;&gt; d_keys
{'fill', 'size', 'angle', 'shape'}
</code></pre>

<p>Or if you are in python2.x you can use <code>dict.viewkeys()</code>:</p>

<pre><code>d_keys = d.viewkeys() - {"inside",}
</code></pre>

<p>But if you want to only remove one item you can use <code>pop()</code> attribute in order to remove the corresponding item from dictionary and then calling the <code>keys()</code>.</p>

<pre><code>&gt;&gt;&gt; d.pop('inside')
'a-&gt;e'
&gt;&gt;&gt; d.keys()
dict_keys(['fill', 'size', 'angle', 'shape'])
</code></pre>

<p>In python 2 since <code>keys()</code> returns a list object you can use <code>remove()</code> attribute for removing an item directly from the keys. </p>

python dictionary