Optimizing dictionaries in Python
<p>My question is different from the one asked <a href="http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended">here</a>. Primarily I am asking what improvements could be made to code containing dictionaries. However, the link explains about memory profilers, which will be my next step.</p>

<p>I have the following two sets of code to achieve the same thing.</p>

<p>First one,</p>

<pre><code>a={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
b=[x for x in a if x in (1,2,3)]
b=['a', 'b', 'c']
</code></pre>

<p>Second one,</p>

<pre><code>a={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
c=[a[x] for x in set(a.keys()) &amp; set([1,2,3])]
b=['a', 'b', 'c']
</code></pre>

<p>I would like to know which one works better in terms of memory optimized methods, and for large sets of data.</p>

<p>Thanks in advance!</p>

<p>If you want to ask among these two, second is better. But overall, both methods have something or other which could be improved. If I had to do something similar, I would have done:</p>

<pre><code>&gt;&gt;&gt; a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
&gt;&gt;&gt; [a[i] for i in (1,2,3) if i in a]
['a', 'b', 'c']
</code></pre>

python python-2.7