Lucian
Lucian

Reputation: 23

make from a list the dictionary lists by key

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?

Upvotes: 2

Views: 111

Answers (3)

thefourtheye
thefourtheye

Reputation: 239463

You can use simple 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 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.

Upvotes: 5

Cony
Cony

Reputation: 41

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

dic = {}
for i in data:
    try:
        dic[i[1]].append(i)
    except:
        dic[i[1]] = []
        dic[i[1]].append(i)

print dic

Output

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

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43235

Use a very simple for loop:

>>> l = ['8C', '2C', 'QC', '5C', '7C', '3C', '6D', 'TD', 'TH', 'AS', 
...  'QS', 'TS', 'JS', 'KS']
>>> my_dict = {}
>>> for x in l:
...     my_dict.setdefault(x[-1],[]).append(x)
... 
>>> my_dict
{'S': ['AS', 'QS', 'TS', 'JS', 'KS'], 'H': ['TH'], 'C': ['8C', '2C', 'QC', '5C', '7C', '3C'], 'D': ['6D', 'TD']}

Upvotes: 2

Related Questions