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>Another option:</p>

<pre><code>filter = lambda arr, x: { x: [ e.get(x) for e in arr] }
</code></pre>

<p>So, from here, you can construct the dict based on the original array and the key </p>

<pre><code> filter(sample_dict, 'a')
# {'a': ['woot', 'coot', 'doot', 'soot', 'toot']}
</code></pre>

python