2
$\begingroup$

I get results from FindInstance as a list of associations.

{{a -> 1, b -> 2}, {a -> 3, b -> 4}}

I would like to sum values by key.

For the example, I would like to get something like {a -> 4, b -> 6}.

$\endgroup$
3
  • 3
    $\begingroup$ Merge[{{a -> 1, b -> 2}, {a -> 3, b -> 4}}, Total]? $\endgroup$ Commented May 22, 2017 at 17:26
  • $\begingroup$ possible duplicate: Adding Rule Solutions $\endgroup$
    – Kuba
    Commented May 22, 2017 at 18:10
  • $\begingroup$ See also (4332) and links therein. $\endgroup$
    – Mr.Wizard
    Commented May 22, 2017 at 21:28

1 Answer 1

1
$\begingroup$
list = {{a -> 1, b -> 2}, {a -> 3, b -> 4}};
Normal@GroupBy[Flatten@list, Keys -> Values, Total];
(* {a -> 4, b -> 6} *)

Thread[Union @@ Keys[#] -> Apply[Plus, Values[#], {1}]]&@ Transpose[list]
(* {a -> 4, b -> 6} *)

as suggested by @J.M.

Normal@Merge[{{a -> 1, b -> 2}, {a -> 3, b -> 4}}, Total] (* applying Normal if you
want the answer with Head list *)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.