Re: dictionaries?
- To: mathgroup at smc.vnet.net
- Subject: [mg20508] Re: dictionaries?
- From: Hans Staugaard <hans.staugaard at get2net.dk>
- Date: Wed, 27 Oct 1999 02:05:04 -0400
- Organization: get2net Internet Kunde
- References: <7v3bov$5tg@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Joe Strout wrote:
>
> In Python, there's an extremely handy datatype called a "dictionary"
> which implements a many-to-1 mapping between keys (which can be any
> hashable type) and values (which can be anything). E.g.:
>
> > d = {"one":1, "two":2}
> > d["one"]
> 1
> > d["three"]
> (key not found)
>
> I'm looking for something similar in Mathematica -- it's a great way to
> organize lists of parameters, without having to worry about the order
> in which they are listed.
>
> I've searched the online help and flipped through the Mathematica book,
> but I can't find anything like this. Have I missed something?
>
> Thanks,
> -- Joe
>
> --
> ,------------------------------------------------------------------.
> | Joseph J. Strout Biocomputing -- The Salk Institute |
> | joe at strout.net http://www.strout.net |
> `------------------------------------------------------------------'
> Check out the Mac Web Directory! http://www.strout.net/macweb.cgi
You could just say
d["one"]=1;
d["two"]=2;
...
or if you have a list like this
dl={"one",1,"two",2,"three",3}
you could do like this
Set[d[#1],#2]&@@@Partition[dl,2]
If you want the function to alert you when there is no key found, you
could, in both cases, add:
d::nokey="Key not found"
d[_]:=Message[d::nokey]
Hope that helps
Hans