Re: associative arrays
- To: mathgroup at smc.vnet.net
- Subject: [mg63890] Re: [mg63858] associative arrays
- From: Hartmut.Wolf at t-systems.com
- Date: Sat, 21 Jan 2006 01:50:37 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
ok, i know from this group that to see keys in a hash (as in per keys
%hash) in would use
keys[hash_] := Map[#[[1, 1, 1]] &, DownValues[hash]];
however, what if i have multiple levels of keys, like
a[levelone][leveltwo]={1,2,3}
a[levelone][level2]={4,5,6}
a[levelA][levelB]={7,8,9}
I need keys[a] to give me {levelone, levelA} and keys[a[levelone]] to
give me {leveltwo, level2}, etc.
Any ideas? Please post. Thx.
-----------------------------
Well,
reading the Book, at A.5.3 you find :
In[5]:=
documentedvalues = {Attributes, DefaultValues, DownValues, FormatValues, \
Messages, NValues, Options, OwnValues, UpValues};
In[6]:= Through[documentedvalues[a]]
Out[6]=
{{}, {}, {}, {}, {}, {}, {}, {}, {}}
So does a really have no values?
Yet there's more...
In[7]:= Names["*Values"]
Out[7]=
{DefaultValues, DownValues, FormatValues, NValues, OwnValues, SingularValues, \
SubValues, UpValues}
The secret is
In[8]:= SubValues[a]
Out[8]=
{HoldPattern[a[levelA][levelB]] :> {7, 8, 9}, HoldPattern[a[levelone][
level2]] :> {4, 5, 6}, HoldPattern[a[levelone][leveltwo]] :> {1, 2, 3}}
Now, how to extract the "keys"?
In[9]:= SubValues[a][[All, 1, 1, 0, 1]]
Out[9]= {levelA, levelone, levelone}
In[10]:= SubValues[a][[All, 1, 1, 1]]
Out[10]= {levelB, level2, leveltwo}
such
In[11]:=
keyPairs = SubValues[a][[All, 1, 1, ##]] & @@@ {{0, 1}, {1}} // Transpose
Out[11]=
{{levelA, levelB}, {levelone, level2}, {levelone, leveltwo}}
--
Hartmut Wolf