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're optimizing for memory use generators are often a good tool. For example:</p>

<pre><code>def get_keys(mapping, keys):
    for key in keys:
        try:
            yield mapping[key]
        except KeyError:
            continue
</code></pre>

<p>On your example:</p>

<pre><code>list(get_keys(a, (1, 2, 3)))
['a', 'b', 'c']
</code></pre>

python python-2.7