# how to construct a dictionary of dictionaries from a list

Anonymous

Given the matrix [0,1,2] [1,0,3] [1,2,4] [0,2,3] [2,4,1] [2,3,2] how to obtain the dictionary D={0:{1:2,2:3},1:{0:3,2:4},2:{3:2,4:1}} ?

edit retag close merge delete

The matrix as a list of rows

( 2012-03-22 06:18:44 +0200 )edit

Sort by ยป oldest newest most voted

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.

more

Thank you very much. Sincerely Eusebio Corbacho

( 2012-03-22 12:51:48 +0200 )edit