Reputation: 9542
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.
Upvotes: 0
Views: 537
Reputation: 3822
from collections import defaultdict
animals=[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'},
{'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]
animal_by_type = defaultdict(list)
for animal in animals:
animal_by_type[animal['type']].append(animal['name'])
print animal_by_type
Upvotes: 0
Reputation: 6776
You can also use a normal dictionary and its setdefault
method:
l = [{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]
d = {}
for x in l:
d.setdefault(x["type"], []).append(x)
print d
The result would be this (nicely formatted):
{'plant' : [{'type': 'plant', 'name': 'orange tree'}],
'animal': [{'type': 'animal', 'name': 'rabbit'},
{'type': 'animal', 'name': 'cow'},
{'type': 'animal', 'name': 'coyote'}]}
Upvotes: 1
Reputation: 289
use defaultdict(list)
, not defaultdict()
. Read the docs for defaultdict to find out more.
Also, you cannot use some_dict.a_key (in your case: .type) - you must use some_dict['a_key'] (in your case ['type'])
Upvotes: 2