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}.
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}.
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 *)
Merge[{{a -> 1, b -> 2}, {a -> 3, b -> 4}}, Total]? – J. M.'s missing motivation May 22 '17 at 17:26