Wolfram Research

AssociatePairs

Contributed by: Taliesin Beynon

Source Notebook

Convert a list of pairs into an association

ResourceFunction["AssociatePairs"][{{key1,val1},{key2,val2},}]

gives the association <|key1val1,key2val2, |>.

Details and Options

The array must be effectively of n×2 dimensions.
AssociatePairs does not reorder the array.

Examples

Basic Examples

Make an association:

In[1]:=
ResourceFunction["AssociatePairs"][{{a, 1}, {b, 2}, {c, 3}}]
Out[1]=

Make an association from two lists:

In[2]:=
ResourceFunction["AssociatePairs"][Transpose[{{a, b, c}, Range[3]}]]
Out[2]=

Applications

The number of moons for each planet in the solar system:

In[3]:=
ResourceFunction["AssociatePairs"][
 PlanetData[#, {"Name", "MoonCount"}] & /@ PlanetData[]]
Out[3]=

Properties and Relations

Equivalent ways to get an association:

In[4]:=
Association @@ Rule @@@ {{"1st", "John"}, {"2nd", "Cat"}, {"3rd", "Joe"}}
Out[5]=
In[6]:=
Association[Thread[{"1st", "2nd", "3rd"} -> {"John", "Bill", "Joe"}]]
Out[6]=

Possible Issues

AssociatePairs does not thread over lists:

In[7]:=
ResourceFunction[
 "AssociatePairs"][{{{r, s}, {t, u}}, {{w, x}, {y, z}}}]
Out[7]=

Resource History