# How to Convert a Matrix into an Association?

I have a matrix like this one:

test = {{1, "a"}, {3, "b"}}


and I want to convert it into an association like this Association[ {1} → "a",{3} → "b" ] for a classify method.

I have tried using { Most @ # -> Last @ #} without success. Any idea?

Thank you.

• Try Association[Most[#] -> Last[#] & /@ test]. May 31, 2016 at 17:01
• AssociationThread @@ Transpose@test
– yode
May 31, 2016 at 17:01
• KeyMap[List]@ %[yode]
– Kuba
May 31, 2016 at 17:02
• Welcome! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign!
– user9660
May 31, 2016 at 17:15
• So combining the answers by Kuba and yode reveals: test // RightComposition[ Transpose, Apply[AssociationThread], KeyMap[List] ] for readability. :)
– gwr
May 31, 2016 at 17:25

Here are a few ways, each returning <| {1} -> "a", {3} -> "b" |>:

Association[{#} -> #2 & @@@ test]

GroupBy[test, Most -> Last, First]

ReplacePart[test, {0 -> Association, {_, 0} -> ({#} -> #2 &)}]

test // Query[Association, Most@# -> Last@# &]

test // Query[GroupBy[Most -> Last], First]


This was my first thought:

AssociationThread @@ Transpose @ test


<|1 -> "a", 3 -> "b"|>

But an undocumented but somewhat slower function also came to mind:

GeneralUtilitiesAssociatePairs[test]


<|1 -> "a", 3 -> "b"|>

### Performance

testlist = RandomInteger[100, {1000000, 2}];
GeneralUtilitiesAssociatePairs[testlist]; // AbsoluteTiming

{1.0462, Null}
{0.160241, Null}
If you want to use lists for keys, you can apply the KeyMap to the result as mentioned in gwr's comment and Kuba's. Then you will get
<|{1} -> "a", {3} -> "b"|>