@@ -169,28 +169,50 @@ def vector_to_set(self, v):
169169 return {id_to_key [index ] for index in indices }
170170
171171
172- def matrix_to_dicts (self , A ):
173- """{row: {col: val}}"""
172+ def matrix_to_dicts (self , A , * , use_row_index = False , use_column_index = False ):
173+ """Convert a Matrix to a dict of dicts of the form ``{row: {col: val}}``
174+
175+ Use ``use_row_index=True`` to return the row index as keys in the dict,
176+ and likewise for `use_column_index=True``.
177+
178+ """
174179 if isinstance (A , TransposedMatrix ):
175180 # Not covered
176181 d = A .T .ss .export ("hypercsc" )
177182 rows = d ["cols" ].tolist ()
178183 col_indices = d ["row_indices" ].tolist ()
184+ use_row_index , use_column_index = use_column_index , use_row_index
179185 else :
180186 d = A .ss .export ("hypercsr" )
181187 rows = d ["rows" ].tolist ()
182188 col_indices = d ["col_indices" ].tolist ()
183189 indptr = d ["indptr" ]
184190 values = d ["values" ].tolist ()
185191 id_to_key = self .id_to_key
186- return {
187- id_to_key [row ]: {
188- id_to_key [col ]: val for col , val in zip (col_indices [start :stop ], values [start :stop ])
192+ it = zip (rows , np .lib .stride_tricks .sliding_window_view (indptr , 2 ).tolist ())
193+ if use_row_index and use_column_index :
194+ return {
195+ row : dict (zip (col_indices [start :stop ], values [start :stop ])) for row , (start , stop ) in it
196+ }
197+ elif use_row_index :
198+ return {
199+ row : {
200+ id_to_key [col ]: val for col , val in zip (col_indices [start :stop ], values [start :stop ])
201+ }
202+ for row , (start , stop ) in it
203+ }
204+ elif use_column_index :
205+ return {
206+ id_to_key [row ]: dict (zip (col_indices [start :stop ], values [start :stop ]))
207+ for row , (start , stop ) in it
208+ }
209+ else :
210+ return {
211+ id_to_key [row ]: {
212+ id_to_key [col ]: val for col , val in zip (col_indices [start :stop ], values [start :stop ])
213+ }
214+ for row , (start , stop ) in it
189215 }
190- for row , (start , stop ) in zip (
191- rows , np .lib .stride_tricks .sliding_window_view (indptr , 2 ).tolist ()
192- )
193- }
194216
195217
196218def to_networkx (self , edge_attribute = "weight" ):
0 commit comments