2

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}.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
montardon
  • 121
  • 1

1 Answers1

1
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 *)
Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42