So I'd like to complement two associations through shared keys... not the best description, so here's an example:

a = <|"a" -> 1, "b" -> 2, "c" -> 3|>
b = <|"a" -> 1, "b" -> 5|>

The questions is, how b differs from a with respect to common keys only, so c doesn't matter.

And by differs I mean, what minimal example of x fulfills:

<|a, x|> ===  <|a, b|>

I could go with:

Complement @@ Normal@{b, a} // Association

but stripping associations seems wrong to me. Is there more generic approach?

p.s. in general case one may want to get inf about missing keys too, then:

 Complement @@ Normal @ KeyUnion[{b, a}]
{"b" -> 5, "c" -> Missing["KeyAbsent", "c"]} 
  • $\begingroup$ Probably wording is not the best so feel free to rename things I've called improperly. $\endgroup$ – Kuba Feb 19 '16 at 12:00
  • 1
    $\begingroup$ Let the question stand so as it is, I like 'em and it is anyway a reference. (+1 anyway) $\endgroup$ – user9660 Feb 19 '16 at 13:42

Complement seems to work without stripping Association in both cases.

Complement[b, a]
(* <|"b" -> 5|> *)

Complement[Sequence @@ KeyUnion[{b, a}]]
(* <|"b" -> 5, "c" -> Missing["KeyAbsent", "c"]|> *)

What version are you using?

  • $\begingroup$ I don't remember the reason why I've assumed it won't work... Now I feel stupid. :) $\endgroup$ – Kuba Feb 19 '16 at 12:37
  • 3
    $\begingroup$ @Kuba Coding fatigue. It happens. $\endgroup$ – Edmund Feb 19 '16 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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