Consider an example Association
:
assoc = <|"a" -> 1, "b" -> "x", "this_key_is_too_long_to_type" -> {1}|>;
Suppose I want to replace "this_key_is_too_long_to_type"
with "c"
. I can replace it by transforming into Normal
land and back into Association
land:
Association[
ReplaceAll[Normal[assoc], Rule["this_key_is_too_long_to_type", rhs_] :> Rule["c", rhs]]]
But I have found with Association
s that there is usually a compact and efficient way and that this double-transformation is usually a signal that I'm not using it. What's the best way to rename a key?
Answer
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.
Comments
Post a Comment