Function Repository Resource:

KeyTakeDrop

Source Notebook

Take and drop particular keys in an association

Contributed by: Daniel Sanchez

ResourceFunction["KeyTakeDrop"][assoc,{key1,key2,}]

gives the pair {assoc1,assoc2}, where assoc1 contains only the elements with keyi and assoc2 contains no elements with keyi.

ResourceFunction["KeyTakeDrop"][{assoc1,assoc2,},{key1,key2,}]

gives a list of association pairs.

ResourceFunction["KeyTakeDrop"][keys]

represents an operator form of ResourceFunction["KeyTakeDrop"] that can be applied to an expression.

Details

In the result {assoc1,assoc2}, assoc1 is an Association object whose elements are in the order of the keyi, whereas assoc2 preserves the original order of elements.
Any keyi that does not appear in assoc is ignored.
ResourceFunction["KeyTakeDrop"] can be applied not only to Association objects, but also to lists of rules.
ResourceFunction["KeyTakeDrop"][keys][expr] is equivalent to ResourceFunction["KeyTakeDrop"][expr,keys].
ResourceFunction["KeyTakeDrop"][assoc,keys] is equivalent to {KeyTake[assoc,keys],KeyDrop[assoc,keys]}.

Examples

Basic Examples (7) 

Take and drop rules from an association, given a list of keys:

In[1]:=
ResourceFunction["KeyTakeDrop"][<|a -> 1, b -> 2, c -> 3|>, {a, b}]
Out[1]=

Take and drop from several associations, given a list of keys:

In[2]:=
ResourceFunction[
 "KeyTakeDrop"][{<|a -> 1, b -> 2|>, <|b -> 2, c -> 3|>}, {a, b}]
Out[2]=

Take and drop rules from a list to create a pair of associations:

In[3]:=
ResourceFunction[
 "KeyTakeDrop"][{1 -> 2, 2 -> 4, 3 -> 9, 4 -> 16, 5 -> 25}, {2, 3}]
Out[3]=

Take and drop rules from several lists:

In[4]:=
ResourceFunction[
 "KeyTakeDrop"][{{1 -> 2, 2 -> 4, 3 -> 9}, {4 -> 16, 5 -> 25}}, {2, 3}]
Out[4]=

Take and drop from an association, using a single key:

In[5]:=
ResourceFunction["KeyTakeDrop"][<|a -> b, c -> d, b -> c|>, c]
Out[5]=

Take and drop from a list, using a single key:

In[6]:=
ResourceFunction["KeyTakeDrop"][{a -> b, b -> c, c -> d}, b]
Out[6]=

Use the operator form of KeyTakeDrop:

In[7]:=
ResourceFunction["KeyTakeDrop"][{a, e}][<|a -> b, c -> d, e -> f, g -> h|>]
Out[7]=

Properties and Relations (1) 

Non-existing keys are ignored:

In[8]:=
ResourceFunction["KeyTakeDrop"][{a -> b, b -> d}, {a, c}]
Out[8]=

Possible Issues (1) 

When a list of rules has a repeated key, only the last value is maintained in the output:

In[9]:=
ResourceFunction["KeyTakeDrop"][{a -> b, a -> c, b -> d}, b]
Out[9]=

Publisher

Daniel Sanchez

Version History

  • 1.0.0 – 08 February 2022

Related Resources

License Information