nutship
nutship

Reputation: 4924

Creating a dictionary from a list

From this list of tuples:

[('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')] 

I want to create a dictionary, which keys will be [0] and [1] value of every third tuple. Thus, the first key of dict created should be 'IND, MIA', second key 'LAA, SUN'

The final result should be:

{'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')],\
'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]}

If this is of any relevance, once the values in question becomes keys, they may be removed from tuple, since then I do not need them anymore. Any suggestions greatly appreciated!

Upvotes: 1

Views: 155

Answers (3)

J0HN
J0HN

Reputation: 26941

inp = [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
       ('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')]

result = {}
for i in range(0, len(inp), 3):
    item = inp[i]
    result[item[0]+","+item[1]] = inp[i:i+3]

print (result)

Dict comprehension solution is possible, but somewhat messy.

To remove keys from array replace second loop line (result[item[0]+ ...) with

result[item[0]+","+item[1]] = [item[2:]]+inp[i+1:i+3]

Dict comprehension solution (a bit less messy than I initially thought :))

rslt = {
    inp[i][0]+", "+inp[i][1]: inp[i:i+3]
    for i in range(0, len(inp), 3)
}

And to add more kosher stuff into the answer, here's some useful links :): defaultdict, dict comprehensions

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

from collections import defaultdict
def solve(lis, skip = 0):
    dic = defaultdict(list)
    it = iter(lis)                    # create an iterator
    for elem in it:
        key = ", ".join(elem[:2])     # create key
        dic[key].append(elem)
        for elem in xrange(skip):     # append the next two items to the 
            dic[key].append(next(it)) # dic as skip =2 
    print dic


solve([('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100'), \
('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')], skip = 2)

output:

defaultdict(<type 'list'>,
 {'LAA, SUN': [('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN')],
 'IND, MIA': [('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')]
 })

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122092

Using the itertools grouper recipe:

from itertools import izip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

{', '.join(g[0][:2]): g for g in grouper(inputlist, 3)}

should do it.

The grouper() method gives us groups of 3 tuples at a time.

Removing the key values from the dictionary values too:

{', '.join(g[0][:2]): (g[0][2:],) + g[1:]  for g in grouper(inputlist, 3)}

Demo on your input:

>>> from pprint import pprint
>>> pprint({', '.join(g[0][:2]): g for g in grouper(inputlist, 3)})
{'IND, MIA': (('IND', 'MIA', '05/30'), ('ND', '07/30'), ('UNA', 'ONA', '100')),
 'LAA, SUN': (('LAA', 'SUN', '05/30'), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}
>>> pprint({', '.join(g[0][:2]): (g[0][2:],) + g[1:]  for g in grouper(inputlist, 3)})
{'IND, MIA': (('05/30',), ('ND', '07/30'), ('UNA', 'ONA', '100')),
 'LAA, SUN': (('05/30',), ('AA', 'SN', '07/29'), ('UAA', 'AAN'))}

Upvotes: 2

Related Questions