python - from matrix to dictionary in single line
- by Sanich
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?