Wolfram: Association. Union, Intersection, Complement, Etc

By Xah Lee. Date: . Last updated: .

Intersection by key

KeyIntersection[ {asso1, asso2, etc} ]
  • Take a list of assos.
  • Return the same list, but each asso is changed.
  • For each asso, only keys that are in all assos, are kept.
xx = Association[ a -> 1, b -> 2 ];
yy = Association[ a -> 9, c -> 3 ];
KeyIntersection [ {xx, yy} ]
(* {<|a -> 1|>, <|a -> 9|>} *)

Complement by key (Association Substraction, Difference)

KeyComplement[ {assoMaster, asso2, asso3, etc} ]
  • Take a list of assos. The first one is the master.
  • Return the master asso, but with keys that exist in other assos removed.
xx = Association[ a -> 1, b -> 2 ];
yy = Association[ a -> 9, c -> 3 ];
KeyComplement[ {xx, yy} ]
(* <|b -> 2|> *)

(* 
key a is removed.
because it exist in other asso
*)

Merge Association and Union

Merge[{assoc1, assoc2, etc}, f]

return a association such that

  • The keys are the union of all keys
  • The value of a key is the merge of all values of that key, combined by f

For example, if keys is k, its value is f[{v1,v2,etc}]

where v1,v2,etc are from different associations all have the same key k. (if a key k is unique, its value is f[{v1}].)

The argument to f is a List, of length 1 or more.

(* merge. combine values to list *)
xx = Association[ a -> 1, b -> 2 ];
yy = Association[ a -> 9, c -> 3 ];
Merge[ {xx, yy}, List ]
(* <|a -> {{1, 9}}, b -> {{2}}, c -> {{3}}|> *)
(* merge. combine values to ff[{...}] *)
xx = Association[ a -> 1, b -> 2 ];
yy = Association[ a -> 9, c -> 3 ];
Merge[ {xx, yy}, ff ]
(* <|a -> ff[{1, 9}], b -> ff[{2}], c -> ff[{3}]|> *)
(* merge. new key's value is the total their values *)
Merge[ {
 Association[ a -> 1, b -> 2 ],
 Association[ a -> 9, c -> 3 ]},
 Total ]
(* <|a -> 10, b -> 2, c -> 3|> *)

Union by Key

KeyUnion[ {asso1, asso2, etc} ]
  • Take a list of assos.
  • Return the same list, but each asso is changed.
  • Each asso have keys of all assos.
  • The new value for a key k that is not originally in asso is Missing[KeyAbsent, k]
(* for each asso, return a new one that has keys in all assos *)
KeyUnion[ {Association[ a -> 1, b -> 2 ], Association[ a -> 9, c -> 3 ]} ]
(*
{<|a -> 1, b -> 2, c -> Missing[KeyAbsent, c]|>,
<|a -> 9, b -> Missing[KeyAbsent, b], c -> 3|>}
*)
KeyUnion[ {asso1, asso2, etc}, f ]

use f[k] for the value of missing key k

(* if a key k is missing, apply ff to k to get a value for it *)
KeyUnion[ {Association[ a -> 1, b -> 2 ], Association[ a -> 9, c -> 3 ]}, ff ]
(* 
{<|a -> 1, b -> 2, c -> ff[c]|>,
<|a -> 9, b -> ff[b], c -> 3|>}
*)

Get a Ordered List of All Values, from All Associations

Catenate[ ListOfAssos ]

join all assos, ignore keys, return a list of their values.

Catenate[
{Association[ a -> 1, b -> 2 ],
Association[ a -> 9, c -> 3 ]}
]
(* {1, 2, 9, 3} *)

other

Wolfram. Association (Key Value List)