Reputation: 21957
I have a list of objects from a django queryset, e.g.
my_list = MyObject.objects.filter(variable=something)
MyObject has a field called year which is set to a particular year, e.g. 2005, 2007, 2009
I want to take my_list and create a dictionary of years which holds all MyObject values for that year. e.g.
my_dict['2005'] = list of objects from my_list which match year = 2005
my_dict['2006'] = list of objects from my_list which match year = 2006
my_dict['2007'] = list of objects from my_list which match year = 2007
my_dict['2008'] = list of objects from my_list which match year = 2008
Can anyone tell me the best way of doing this. I already have the first bit sorted, e.g getting my_list. I just need it splitting down into years. I have attempted to write it myself but it became very inefficient with a lot of for loops and db queries
Thanks
Upvotes: 0
Views: 9564
Reputation: 599956
(Don't call the queryset 'my_list', it's not actually a list but a queryset. Call it something like 'my_objects'.)
my_dict = {}
for obj in my_objects:
my_dict.setdefault(obj.year, []).append(obj)
Upvotes: 1
Reputation: 882621
import collections
mydict = collections.defaultdict(list)
for obj in my_list:
mydict[obj.year].append(obj)
Upvotes: 4