MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Re: associative arrays


Ed Peschko wrote:
> On Mon, Jun 20, 2005 at 09:05:21AM -0400, Sseziwa Mukasa wrote:
> 
>>On Jun 19, 2005, at 3:44 AM, Ed Peschko wrote:
>>
>>
>>>hey all,
>>>
>>>Is there a simple way to make an associative array in mathematica?
>>>
>>>I noticed that there's a sparse array, but I'd like to be able to
>>>use a non-numeric value as key..
>>
>>Don't use arrays, use pattern matching eg:
>>
>>f[key1]=value1
>>f[key2]=value2
>>.
> 
> 
> that does some things that I want, but I'm not sure if this is a 'true' 
> associative array, like perl's or python's dictionaries..
> 
> Can you:
> 
> 	a) list the keys in a given order, and iterate over them?
> 	b) do true, multi-dimentional hashes, where both the key and 
>            the value of the hash are either other hashes, or lists?
> 
> 
> I know you can do ?f to list the values, but I'd like to be able to do
> the 2 items above programatically.
> 
> Ed

You can extract keys using DownValues, as below.

In[1]:= f[key1]=value1;

In[2]:= f[key2]=value2;

In[4]:= f[key0]=value0;

In[5]:= DownValues[f]
Out[5]= {HoldPattern[f[key0]] :> value0, HoldPattern[f[key1]] :> value1,
     HoldPattern[f[key2]] :> value2}

In[6]:= Map[#[[1,1,1]]&, DownValues[f]]
Out[6]= {key0, key1, key2}

You can now iterate over this list. If it were huge such that presorting 
might affect speed of doing DownValues, you can do it via 
DownValues[...,Sort->False]. Lists can be used as keys.

In[9]:= f[{1,2,3}] = {a,b,c,f,key1};

In[10]:= DownValues[f,Sort->False]
Out[10]= {HoldPattern[f[key1]] :> value1,
   HoldPattern[f[key2]] :> value2,
   HoldPattern[f[key0]] :> value0,
   HoldPattern[f[{1, 2, 3}]] :> {a, b, c, f, key1}}


Daniel Lichtblau
Wolfram Research


  • Prev by Date: Re: plot
  • Next by Date: Re: Transformation rule problem
  • Previous by thread: Re: associative arrays
  • Next by thread: Re: associative arrays