# From a list to a list of rules

Starting from these two lists,

var = {a, b, c}
values = {{1, 2, 3}, {4, 5, 6}, {7, 8 , 9}}


how can I generate a list of rules?

rules = {{a -> 1, b -> 2, c -> 3}, {a -> 4, b -> 5, c -> 6}, {a -> 7, b -> 8, c -> 9}}


This is how far I have got

In: {{a, b, c}, {1, 2, 3}} // Transpose
In: Rule @@@ %
Out: {{a, 1}, {b, 2}, {c, 3}}
Out: {a -> 1, b -> 2, c -> 3}

-

Another way:

Thread[var -> #] & /@ values

-
Cleaner: Thread[var -> #] & /@ values – Mr.Wizard Mar 16 '12 at 9:51
@Mr.Wizard Okay. – Szabolcs Mar 16 '12 at 10:06

I propose using Inner:

Inner[Rule, var, values\[Transpose], List]


This is faster than other methods presented:

SetAttributes[timeAvg, HoldFirst]

timeAvg[func_] :=
Do[If[# > 0.3, Return[#/5^i]] & @@ Timing @ Do[func, {5^i}], {i, 0, 15}]

var = Range@70;
values = Array[Times, {500, 70}];

Inner[Rule, var, values\[Transpose], List]; // timeAvg
Map[Rule @@@ Transpose[{var, #}] &, values]; // timeAvg
Thread[var -> #] & /@ values; // timeAvg
MapThread[Rule, {var, #}] & /@ values; // timeAvg

0.009736

0.01248

0.01372

0.01248

-
Would you mind editing in the definition of timeAvg? – Yves Klett Mar 16 '12 at 9:25
@Yves I put at link at the bottom; is that good enough? – Mr.Wizard Mar 16 '12 at 9:26
Sure! Perhaps for the casual sloppy Paste&Evaluate user (i.e. me) actually putting it in would be more convenient. – Yves Klett Mar 16 '12 at 9:32
@Yves done as requested. – Mr.Wizard Mar 16 '12 at 9:44
Still another possibility: Inner[#2 -> #1 &, values, var, List] – J. M. Oct 27 '12 at 2:08

Just do a map on the values, like this:

var = {a, b, c}
values = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Map[Rule @@@ Transpose[{var, #}] &, values]


This is the output: {{a -> 1, b -> 2, c -> 3}, {a -> 4, b -> 5, c -> 6}, {a -> 7, b -> 8, c -> 9}}

(In your question you have c->5, but I'm assuming this is a mistake:)

-
thanks, I changed the numbers – sjdh Mar 16 '12 at 8:56
I would use Thread[var -> #]&, or Thread[ Rule[ var, # ]]&, if you prefer, as the function being mapped. It accomplishes the same thing with less code. I'd even be tempted to rewrite it as Thread[var -> #]& /@ values to take advantage of the shorthand notation. – rcollyer Mar 16 '12 at 19:19

Another alternative:

MapThread[#1 -> #2 &, {var, #}] & /@ values


or, equivalently

MapThread[Rule, {var, #}] & /@ values

-

Just for fun, another alternative using Outer:

Flatten[Outer[Thread[#1 -> #2] &, {var}, values, 1], 1]

-
AssociationThread[var, #] & /@ values // Normal


{{a->1,b->2,c->3},{a->4,b->5,c->6},{a->7,b->8,c->9}}

Just for record

GeneralUtilitiesAssociatePairs[Transpose[{var, #}]] & /@ values // Normal
`

{{a->1,b->2,c->3},{a->4,b->5,c->6},{a->7,b->8,c->9}}

-