5
$\begingroup$

This question already has an answer here:

I have a "sparse array" like this

arr[1.5]=0.4, arr[3.5]=0.7, arr[7]=0.3

which is not really a sparse array since the keys are not all integers. This is like a hash table or associative array.

How can I convert arr into a list? I tried Normal[arr], but it won't work. I would like to be able to compute Total@arr, but first it needs to be converted to a normal list.

$\endgroup$

marked as duplicate by Mr.Wizard May 3 '13 at 3:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ In fact this is exactly a hash table. $\endgroup$ – Oleksandr R. May 2 '13 at 20:21
9
$\begingroup$

This might be the general sort of operation you seek.

keyvalpairs = 
 DownValues[arr] /. Verbatim[HoldPattern][arr[k_]] :> k

(* Out[121]= {1.5 :> 0.4, 3.5 :> 0.7, 7 :> 0.3} *)
$\endgroup$
  • $\begingroup$ I was trying to do exactly that but I couldn't figure out the pattern/replacement I needed +1. $\endgroup$ – s0rce May 3 '13 at 0:53
  • $\begingroup$ @sOrce it took me a few tries. That combination of HoldPattern and Verbatim is not something I am accustomed to needing. $\endgroup$ – Daniel Lichtblau May 3 '13 at 14:56
8
$\begingroup$

Here is one way to do it:

{arr[1.5] = 0.4, arr[3.5] = 0.7, arr[7] = 0.3}
Total[DownValues[arr][[All, 2]]]
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.