MathGroup Archive 1999

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

Search the Archive

Re: dictionaries?


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


  • Prev by Date: Re: Basic Laplace Transforms
  • Next by Date: Re: Separating
  • Previous by thread: Re: dictionaries?
  • Next by thread: Re: Re: dictionaries?