How can a key be renamed in an Association?

Somewhat similar to the answer of evanb, but without explicit mutations:

keyRename[a_, old_ -> new_] /; KeyExistsQ[a, old] := KeyDrop[old]@Append[a, new -> a[old]]

So that

keyRename[assoc, "this_key_is_too_long_to_type" -> "c"]

(* <|"a" -> 1, "b" -> "x", "c" -> {1}|> *)

It should be noted that this solution doesn't preserve the order of the keys. A variant that does is:

keyRename[a_, key_ -> key_] := a
keyRename[a_, old_ -> new_] /; KeyExistsQ[a, old] := 
        KeyDrop[old]@Insert[asc, new -> asc[old], Key[old]]

There is, of course:

assoc = <|"a" -> 1, "b" -> "x", "this_key_is_too_long_to_type" -> {1}|>;
assoc["c"] = assoc["this_key_is_too_long_to_type"];
assoc["this_key_is_too_long_to_type"] =.
assoc
(* <|"a" -> 1, "b" -> "x", "c" -> {1}|> *)

Not sure if there's an elegant way to do it in one step.


Here's a way to do it in one line without using Normal first.

KeyMap[If[SameQ[#, "this_key_is_too_long_to_type"], "c", #] &, assoc]

Or:

KeyMap[# /. "this_key_is_too_long_to_type" -> "c" &, assoc]

Tags:

Associations