Adding multiple key,value pair using dictionary comprehension
<p>for a list of dictionaries</p>

<pre><code>sample_dict = [
{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'},
{'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'},
{'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'},
{'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'},
{'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'}
]
</code></pre>

<p>How do I make a separate dictionary that contains all the key,value pair that match to a certain key. With list comprehension I created a list of all the key,value pairs like this:</p>

<pre><code>container = [[key,val] for s in sample_dict for key,val in s.iteritems() if key == 'a']
</code></pre>

<p>Now the container gave me</p>

<pre><code>[['a', 'woot'], ['a', 'coot'], ['a', 'doot'], ['a', 'soot'], ['a', 'toot']]
</code></pre>

<p>Which is all fine... but if I want to do the same with dictionaries, I get only a singe key,value pair. Why does this happen ?</p>

<pre><code>container = {key : val for s in sample_dict for key,val in s.iteritems() if key == 'a'}
</code></pre>

<p>The container gives only a single element</p>

<pre><code>{'a': 'toot'}
</code></pre>

<p>I want the something like </p>

<pre><code>{'a': ['woot','coot','doot','soot','toot']}
</code></pre>

<p>How do I do this with minimal change to the code above ? </p>

<p>You are generating multiple key-value pairs with the same key, and a dictionary will only ever store <em>unique</em> keys.</p>

<p>If you wanted just <em>one</em> key, you'd use a dictionary with a list comprehension:</p>

<pre><code>container = {'a': [s['a'] for s in sample_dict if 'a' in s]}
</code></pre>

<p>Note that there is <em>no need</em> to iterate over the nested dictionaries in <code>sample_dict</code> if all you wanted was a specific key; in the above I simply test if the key exists (<code>'a' in s</code>) and extract the value for that key with <code>s['a']</code>. This is <em>much faster</em> than looping over all the keys.</p>

python