I am trying to group the items in a dictionary by a particular key, let's say we have the following dictionary:
[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]
And I wanted to group these items by type
. According to this answer this can be done using defaultdict()
because it doesn't raise a KeyError
, as follows:
grouped = defaultdict()
for item in items:
grouped[item.type].append(item)
However, I am actually getting a KeyError
.
So what's wrong? All the information I see says defaultdict()
is supposed to create an empty list if it's not existing, and the insert the element.
I am using Python 2.7.