Grouping dictionary items by attribute
<p>I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:</p>

<pre><code>[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]
</code></pre>

<p>And I wanted to group these items by <code>type</code>. According to <a href="http://stackoverflow.com/questions/6602172/how-to-group-a-list-of-tuples-objects-by-similar-index-attribute-in-python">this answer</a> this can be done using <code>defaultdict()</code> because it doesn't raise a <code>KeyError</code>, as follows:</p>

<pre><code>grouped = defaultdict()
for item in items:
    grouped[item.type].append(item)
</code></pre>

<p>However, I am actually getting a <code>KeyError</code>.</p>

<p>So what's wrong? All the information I see says <code>defaultdict()</code> is supposed to create an empty list if it's not existing, and the insert the element.</p>

<p>I am using Python 2.7.</p>

<p>use <code>defaultdict(list)</code>, not <code>defaultdict()</code>. Read the docs for defaultdict to find out more.</p>

<p>Also, you cannot use some_dict.a_key (in your case: .type) - you must use some_dict['a_key'] (in your case ['type'])</p>

python dictionary