views:

241

answers:

3

Hi All

I want to use a Structure like HashTable. Is there similar structure in Wolfram Mathematic?

Best Regards,

+1  A: 

I'd say the most similar structure you can get out of the box are sparse arrays.

JG
+5  A: 

There are a number of possibilities. The easiest possibility, which works well if you don't need to add or delete keys from your table, or change their associated values, is to construct a list of rules with the key on the left-hand side and the value on the right-hand side, and use Dispatch on it.

If you do need to change the entries in your table, you can use the DownValues of a symbol as a hash table. This will support all the operations one commonly uses with hash tables. Here's the most straightforward way of doing that:

(* Set some values in your table.*) 
In[1]:=  table[a] = foo; table[b] = bar; table[c] = baz;

(* Test whether some keys are present. *)
In[2]:=  {ValueQ[table[a]], ValueQ[table[d]]}
Out[2]:= {True, False}

(* Get a list of all keys and values, as delayed rules. *)
In[3]:=  DownValues[table]
Out[3]:= {HoldPattern[table[a]] :> foo, HoldPattern[table[b]] :> bar,
HoldPattern[table[c]] :> baz}

(* Remove a key from your table. *)
In[4]:=  Unset[table[b]]; ValueQ[table[b]]
Out[4]:= False
Pillsy
+1  A: 

I agree with Pillsy, but see also this answer:

http://stackoverflow.com/questions/135330/mathematica-downvalue-lhs/154704#154704

It includes a handy function for getting the keys of a hash table.

dreeves