python - from matrix to dictionary in single line

Posted by Sanich on Stack Overflow See other posts from Stack Overflow or by Sanich
Published on 2012-06-01T22:28:43Z Indexed on 2012/06/01 22:40 UTC
Read the original article Hit count: 203

matrix

is a list of lists. I've to return a dictionary of the form

{i:(l1[i],l2[i],...,lm[i])}

Where the key i is matched with a tuple the i'th elements from each list. Say

matrix=[[1,2,3,4],[9,8,7,6],[4,8,2,6]]

so the line:

>>> dict([(i,tuple(matrix[k][i] for k in xrange(len(matrix)))) for i in xrange(len(matrix[0]))])

does the job pretty well and outputs:

{0: (1, 9, 4), 1: (2, 8, 8), 2: (3, 7, 2), 3: (4, 6, 6)}

but fails if the matrix is empty: matrix=[]. The output should be: {}

How can i deal with this?

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary