5
$\begingroup$

Considering following nested structure:

ls = {"a" -> 1,
      "b" -> 2,
      "c" -> {"AA" -> <|"Aaaa" -> <|"yi" -> 512, "h"  -> 45           |>, 
                           "V" -> <|"e2" ->   5, "rr" -> <|"e"->3.14|>|>|>,
              "VV" -> <|  "e4" -> 123|>}}

I want to update "e4" key to have 124 value instead of 123.

I can easily extract the value by "VV" /. ("c" /. ls). I can even update the value as follows:

Insert["VV" /. ("c" /. ls), "e4" -> 124, -1]

This nohow affects the ls.

What is the correct way to update the value exactly in ls?

Thanks!

$\endgroup$
2
  • 1
    $\begingroup$ Do you have to work with this mixed form? $\endgroup$
    – Kuba
    Commented Oct 20, 2015 at 11:30
  • $\begingroup$ If you mean the mix of lists and associations, then yes $\endgroup$
    – SuTron
    Commented Oct 20, 2015 at 11:36

1 Answer 1

2
$\begingroup$

You need to use Part to be able to change list elements. For a list of rules you can use this index finder:

RulesIndex[ls_List, keys_List] := 
  Sequence @@ 
   Flatten@FoldPairList[
     With[{pos = 
         FirstPosition[#1, #2 -> _, Missing@"NotFound", 1]~Append~
          2}, {pos, Extract[#1, pos]}] &, ls, keys];

ls[[RulesIndex[ls, {"c", "VV"}]]][["e4"]] = 124

which is the same as

ls[[3, 2, 2, 2, "e4"]] = 124
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.