make from a list the dictionary lists by key
Question: I have a list:

    
    
    ['8C', '2C', 'QC', '5C', '7C', '3C', '6D', 'TD', 'TH', 'AS', 
     'QS', 'TS', 'JS', 'KS']
    

I need to get a dictionary something like this: (sorting is not important)

    
    
    {'C': ['QC', '8C', '7C', '5C', '3C', '2C'], 
     'S': ['AS', 'KS', 'QS', 'JS', 'TS']
    }
    

code:

    
    
    def parse_flush(cards):
        cards = sort_by_color(cards)
        flush_dic = {}
        print str(cards)
        count = 0
        pos = 0
        last_index = 0
        for color in colors:
            for i, card in enumerate(cards):
                if card[1] == color:
                    count += 1
                    last_index = i+1
                    if count == 1:
                        pos = i
            if count >= 5:
                flush_dic[color] = sort_high_to_low(cards[pos:last_index])
            count = 0
        return flush_dic
    

my code now looks like, it works but I do not like its length it is possible
to make it shorter using python tricks?


Answer: You can use simple
[`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict)
to get the results you wanted

    
    
    from collections import defaultdict
    result = defaultdict(list)
    for item in data:
        result[item[1]].append(item)
    print result
    

**Output**

    
    
    {'S': ['AS', 'QS', 'TS', 'JS', 'KS'],
     'H': ['TH'],
     'C': ['8C', '2C', 'QC', '5C', '7C', '3C'],
     'D': ['6D', 'TD']}
    

You can solve this, using
[`itertools.groupby`](http://docs.python.org/2/library/itertools.html?highlight=itertools#itertools.groupby)
as well

    
    
    data = ['8C', '2C', 'QC', '5C', '7C', '3C', '6D', 'TD', 'TH', 'AS', 'QS',
            'TS', 'JS', 'KS']
    
    from itertools import groupby
    from operator import itemgetter
    keyFn = itemgetter(1)
    print {k:list(grp) for k, grp in groupby(sorted(data, key = keyFn), keyFn)}
    

**Explanation**

`sorted` returns a sorted list of items, and it uses `keyFn` for sorting the
data.

`groupby` accepts a sorted list and it groups the items based on the `keyFn`,
in this case `keyFn` returns the second elements for each and every items and
the result is as seen in the output.

