Function Repository Resource:

# KeyReplace

Replace keys in an association

Contributed by: Richard Hennigan (Wolfram Research)
 ResourceFunction["KeyReplace"][assoc,rules] applies a rule or list of rules in an attempt to transform the keys of assoc. ResourceFunction["KeyReplace"][assoc,rules,levelspec] applies rules to keys at levels specified by levelspec. ResourceFunction["KeyReplace"][rules] represents an operator form of KeyReplace that can be applied to an expression.

## Details and Options

The rules must be of the form lhsrhs or lhsrhs.
A list of rules can be given. The rules are tried in order. The result of the first one that applies is returned. If none of the rules apply, the original assoc is returned.
Delayed rules defined with can contain /; conditions.
KeyReplace uses standard level specifications:
 n levels 1 through n Infinity levels 1 through Infinity All all levels, including zero {n} level n only {n1,n2} levels n1 through n2
The default value for levelspec in KeyReplace is {0}, corresponding to the whole expression.
A positive level n consists of all parts of assoc specified by n indices.
A negative level -n consists of all parts of assoc with depth n.
Level -1 consists of numbers, symbols and other objects that do not have subparts.
If levelspec includes multiple levels, expressions at deeper levels in a given subexpression are matched first.
With the option setting , KeyReplace includes heads of expressions and their parts.
Replacements are performed to parts specified by levelspec even when those parts have Hold or related wrappers.
KeyReplace[rules][expr] is equivalent to KeyReplace[expr,rules].

## Examples

### Basic Examples (6)

Replace a key in an Association:

 In[1]:=
 Out[1]=

Replace a key in a list of rules:

 In[2]:=
 Out[2]=

Replace multiple keys:

 In[3]:=
 Out[3]=

Use the operator form of KeyReplace:

 In[4]:=
 Out[4]=

Replace keys at deeper levels in the expression:

 In[5]:=
 Out[5]=

Use RuleDelayed to replace keys without evaluation:

 In[6]:=
 Out[6]=

### Scope (3)

Retrieve the ResourceFunction:

 In[7]:=
 Out[7]=

Retrieve the ResourceObject:

 In[8]:=
 Out[8]=

Use patterns for key replacements:

 In[9]:=
 Out[9]=

### Applications (1)

Rename keys in data:

 In[10]:=
 Out[10]=
 In[11]:=
 Out[11]=

### Properties and Relations (2)

KeyReplace avoids unpacking/evaluating initialized associations:

 In[12]:=
 Out[12]=
 In[13]:=
 Out[13]=

This avoids potentially undesired evaluation leaks in some other methods:

 In[14]:=
 Out[14]=

### Possible Issues (2)

When multiple keys match a given pattern, only the first key that matches is replaced:

 In[15]:=
 Out[15]=

Replacements may need to be repeated in order to get all the keys:

 In[16]:=
 Out[16]=

## Requirements

Wolfram Language 11.3 (March 2018) or above

## Version History

• 1.0.0 – 31 August 2018