Python: How can I group this list of items by category?
Question: Working with a Django app. I have a List of `ads` and I want to be able to
filter on these in templates (eg, grab all ads of `spot_id = 1`, then pick a
random one.

I'm using raw SQL via the cursor instead of Django's mysterious querying, so I
already have my list (converted into a dict). Here's what I have so far:

    
    
    # list/dict of ads
    [
     {'filename': u'rc_ad_06_02_11.gif', 'spot_id': 1L }, 
     {'filename': u'k_banner.jpg', 'spot_id': 1L}, 
     {'filename': u'dwarves-banner.gif', 'spot_id': 1L}, 
     {'filename': u'k_skyscraper.jpg', 'spot_id': 2L }
    ]   
    
    # attempt to group them somehow
    final_ads = []
    
        last_spot_id = 0
        for a in ads:
            if a['spot_id'] != last_spot_id:
            final_ads[a['spot_id']][] = a # syntax error here
        last_spot_id = a['spot_id']
    
    logger.info(final_ads)
    

This doesn't work. What I'm essentially trying to get to is a list of this
kind of structure:

    
    
    [
     1: [
         {'filename': u'rc_ad_06_02_11.gif', 'spot_id': 1L }, 
         {'filename': u'k_banner.jpg', 'spot_id': 1L}, 
         {'filename': u'dwarves-banner.gif', 'spot_id': 1L}
     ],
     2: [
         {'filename': u'k_skyscraper.jpg', 'spot_id': 2L }
     ]
    ]   
    

(couldn't think of a proper way of representing this, sorry if it doesn't look
right).

If anyone can show me a smarter way of doing this I'd be very appreciative.
Thanks.


Answer: defaultdict should handle this nice it will return a dict rather than a list

final_ads will be something like {1:[a1,a3,a4],2:[a2,a5]...}

    
    
    from collections import defaultdict
    final_ads = defaultdict(list)
    for a in ads:
        final_ads[a['spot_id']].append(a)
    
    print final_ads
    for spot_id in sorted(final_ads.keys()):
        print "Spot %s=%s"%(spot_id,final_ads[spot_id])
    

above code with your list of dicts ~~returns~~ prints

    
    
    defaultdict(<type 'list'>, {1L: [{'spot_id': 1L, 'filename': u'rc_ad_06_02_11.gif'}, {'spot_id': 1L, 'filename': u'k_banner.jpg'}, {'spot_id': 1L, 'filename': u'dwarves-banner.gif'}], 2L: [{'spot_id': 2L, 'filename': u'k_skyscraper.jpg'}]})
    Spot 1=[{'spot_id': 1L, 'filename': u'rc_ad_06_02_11.gif'}, {'spot_id': 1L, 'filename': u'k_banner.jpg'}, {'spot_id': 1L, 'filename': u'dwarves-banner.gif'}]
    Spot 2=[{'spot_id': 2L, 'filename': u'k_skyscraper.jpg'}]
    

