Ask Your Question
0

how to construct a dictionary of dictionaries from a list

asked 2012-03-22 06:16:14 +0100

anonymous user

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 flag offensive close merge delete

Comments

The matrix as a list of rows

canisvetus gravatar imagecanisvetus ( 2012-03-22 06:18:44 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2012-03-22 07:31:18 +0100

DSM gravatar image

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.

edit flag offensive delete link more

Comments

Thank you very much. Sincerely Eusebio Corbacho

canisvetus gravatar imagecanisvetus ( 2012-03-22 12:51:48 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-03-22 06:16:14 +0100

Seen: 947 times

Last updated: Mar 22 '12