WolframLang: Association: Filter

By Xah Lee. Date: . Last updated: .

Truncate Association

Take[ asso, n ]

take first n items.

Take

xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

Take[ xx, 2 ] === <|a -> 1, b -> 2|>

Filter by Key, with List of Keys

KeyTake[asso, listOfKeys]

return an association containing only the elements with given keys.

KeyTake

xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

KeyTake[ xx, {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, with a Function

KeySelect[asso, crit]

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

KeySelect

xx = Association[ 1 -> a, 2 -> b, 3 -> c, 4 -> d ];

KeySelect[ xx, EvenQ ] === <|2 -> b, 4 -> d|>

KeySelect[ xx, Function[ x, Mod[x,3] === 0 ] ] === <|3 -> c|>

Filter by Value, Using a Function

Select[ asso, f]

filter asso by function f applied to values that return true.

Select

xx = Association[ a -> 1, b -> 2, c -> 3, d -> 4 ];

Select[ xx, EvenQ ] === <|b -> 2, d -> 4|>

WolframLang: Association (Key Value List)