POOJA GUPTA
POOJA GUPTA

Reputation: 2355

How to store the sql query result into a dictionary object

I have sql query result like :

result = [['a',21/1/2015,2],['a',22/1/2015,3],['b',21/1/2015,2],['b',22/1/2015,2],['b',24/1/2015,1],['b',26/1/2015,9],['b',27/1/2015,8],['b',28/1/2015,5],['b',21/1/2015,2]]

where first element in each sublist(or row) could appear maximum 7 times. I want to store the result in a dictionary object such that each element of the dictionary object has the key as the first element in the sublist and the value will be the list of size 7 maximum with values as the third element in each sublist. For eg :

{'a' : [2,3,0,0,0,0,0],'b':[2,2,1,9,8,5,2]}

How can I do this?

Upvotes: 0

Views: 1042

Answers (1)

C S
C S

Reputation: 1525

d = {}
for x in result:
    d.setdefault(x[0], [] ).append(x[2])
for x in d:
    while len(d[x]) < 7:
        d[x].append(0)

Upvotes: 2

Related Questions