1 | initial version |
One simple way would be to loop over the rows:
m = Matrix([[0,1,2], [1,0,3] ,[1,2,4], [0,2,3], [2,4,1], [2,3,2]])
newdict = {}
for a,b,c in m:
if a not in newdict:
newdict[a] = {}
newdict[a][b] = c
sage: newdict
{0: {1: 2, 2: 3}, 1: {0: 3, 2: 4}, 2: {3: 2, 4: 1}}
Those of us who learned Python before we came to Sage will often write this as
from collections import defaultdict
newdict = defaultdict(dict)
for a,b,c in m:
newdict[a][b] = c
instead: a defaultdict is a dictionary which automatically makes a new value (in this case of type "dict") whenever a key that hasn't been seen yet is asked for. It's handy for avoiding a lot of branching to handle uninitialized entries.