defaultdict to count items in Django
One of the great things I discovered today is defaultdict(). This allows one to create dictionaries with a count for each item in a very compact and powerful way. Look at this:
>>> for item in NoticeQueueBatchByUser.objects.filter(user=3).values(‘label’,'on_site’):… d[item['label']] += 1…>>> d.items()[(u'pagedisplay_violation', 4)]>>>>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for item in ExampleModel.objects.values(‘label’,'other_info’):
… d[item['label']] += 1
…
>>> d.items()
[(u'key_1', 4),(u'another_key',2)]
>>>
This will give you the number of times each label appears in ExampleModel.objects.values(‘label’,'other_info’)
This entry was posted on Thursday, August 27th, 2009 at 6:10 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.