Wolfram: Association. Delete Items by Filter

By Xah Lee. Date: . Last updated: .

Filter by Key, via List of Keys

KeyTake[asso, listOfKeys]

return an association containing only the elements with given keys.

KeyTake[
Association[ a -> 1, b -> 2, c -> 3, d -> 4 ],
{a, c} ]
(* <|a -> 1, c -> 3|> *)
KeyTake[listOfAssoc, listOfKeys]

gives a list of associations.

xx = {
Association[ a -> 1, b -> 2, c -> 3, d -> 4 ],
Association[ a -> 10, b -> 20, c -> 30, d -> 40 ]
};
KeyTake[ xx, {a, c} ]
(* {<|a -> 1, c -> 3|>, <|a -> 10, c -> 30|>} *)

Filter by Key, via a Function

KeySelect[asso, crit]

return a new assoc such that Function crit return True on keys.

KeySelect[
Association[ 1 -> a, 2 -> b, 3 -> c, 4 -> d ],
EvenQ ]
(* <|2 -> b, 4 -> d|> *)

KeySelect[
Association[ 1 -> a, 2 -> b, 3 -> c, 4 -> d ],
Function[ x, Mod[x,3] === 0 ] ]
(* <|3 -> c|> *)

Filter by Values, via a Function

Select
  • Select[ asso, f] → get items where f return true on the values.
  • Select[ asso, f, n] → get first n.
Select[
Association[ a -> 1, b -> 2, c -> 3, d -> 4 ],
EvenQ ]
(* <|b -> 2, d -> 4|> *)

Wolfram. Association (Key Value List)