3
$\begingroup$

I have two association lists, whose values are integers, sharing some but not all keys. For a small example, we might have

A=<|x->1, y->2, z->3|>;
B=<|y->-2, z->7, w->0|>;

I would like to "add" the two association lists, by adding values when they share a common key, but also I would like to drop any keys whose values are 0. Thus, for my example I would want

Add(A,B)=<|x->1, z->10|>;

I can think of some ways to accomplish these tasks, but they are somewhat slow. Any advice?


Edited to add: In practice the list A is much longer than the list B, and has no zero values. I'm going to replace A by Add(A,B) anyway, so it might be faster to update A using B in some way.

$\endgroup$

2 Answers 2

4
$\begingroup$

One way to do it.

Merge[{A, B}, Total] // Select[# != 0 &]
(* <|x -> 1, z -> 10|> *)

If there are no 0 values in A you might want to remove the 0's from B before the Merge.

$\endgroup$
3
$\begingroup$

Merge[{A, B}, Total] // DeleteCases@0

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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