1

I have to define a huge sparse matrix, which row index of the matrix is a 5 vector of size 5 and column index of of the matrix is also a vector of size 5. To be more specific, To retrieve an element in this matrix I need to know two vectors:

  1. One is a vector for row, let's call it (i,j,k,l,m). Where i=1,...,20,j=1,...,10, k=1,...,10, l=1,...,10, m=1,...,10.
  2. One for column, let's call it (n,o,p,q,r). Where Similarly, n=1,...,20, o=1,...,10, p=1,...,10, q=1,...,10, r=1,...,10.

    I am trying to implement the idea of dictionary of dictionaries where each key of the Dict_1 dictionary refers to another dictionary, let's call it Dict_2. Where keys of Dict_1 are vectors for row and keys of Dict_2 are vectors for column.

I really appreciate any hint or help in defining this dictionary. I look into What is the best way to implement nested dictionaries in Python? but couldn't figure out how to extend that idea to the case where my row and column keys are vectors. I really appreciate any help, comment.

Community
  • 1
  • 1
NNsr
  • 1,023
  • 2
  • 11
  • 25

1 Answers1

1

Why not have your dictionary like so:

matrix = { (v1,v2):val}

So for example:

>>> m = {((1,2,3,4),(9,8,8,2)):"info"}
>>> m[((1,2,3,4),(9,8,8,2))]
'info'

If you required a setup like: matrix = { v1: { v2:val }}, you might use a deafultdict like so:

>>> matrix = defaultdict(dict)
>>> matrix[(1,2,3,4)][(9,8,8,2)] = "info"
>>> matrix
defaultdict(<type 'dict'>, {(1, 2, 3, 4): {(9, 8, 8, 2): 'info'}})
>>> matrix[(1,2,3,4)][(9,8,8,2)]
'info'
HennyH
  • 7,794
  • 2
  • 29
  • 39
  • Thank you; this helps a lot. Just another quick question. Is it possible to do similar thing with dok_matrix from scipy? I am dealing with sparse matrices and it would help if I can use scipy's tools. I tried the following, but got errors: from collections import defaultdict from scipy.sparse import * from scipy import * S = dok_matrix((9,9)) for i in range(3): for j in range(3): for k in range(3): for l in range(3): S[(i,j)][(k,l)]=i+j+k+l – NNsr Jul 08 '13 at 05:48