1
$\begingroup$

I have the following association, assoc:

assoc = <|{0} -> {1}, {1} -> {2, 3, 5, 7}, {2} -> {4, 9},  {1, 1} -> {<|{2, "p"} -> {6}|>, <|{3, "p"} -> {15}|>}, {3} -> {8}|>

This assoc was built as follows:

init := <| {0} -> {1} |>
nPtL[ps_, n_] := ps -> {n}
nAPL[as_, ls_] := Association[as, ls]
assoc = nAPL[init, nPtL[{1}, 2]];
assoc[{1}] = Append[assoc[{1}], 3];
assoc = nAPL[assoc, nPtL[{2}, 4]];
assoc[{1}] = Append[assoc[{1}], 5];
tas1 = <|{2, "p"} -> {6}|>;
assoc = nAPL[assoc, nPtL[{1, 1}, tas1]];
assoc[{1}] = Append[assoc[{1}], 7];
assoc = nAPL[assoc, nPtL[{3}, 8]];
assoc[{2}] = Append[assoc[{2}], 9];
tas2 = <|{3, "p"} -> {15}|>;
assoc[{1, 1}] = Append[assoc[{1, 1}], tas2];
assoc

My question is as follows. How can I, efficiently, change the assoc to:

assoc = <|{0} -> {1}, {1} -> {2, 3, 5, 7}, {2} -> {4, 9},  {1, 1} -> {<|{2, "p"} -> {6, 10}|>, <|{3, "p"} -> {15}|>}, {3} -> {8}|>

That is update

 {1, 1} -> {<|{2, "p"} -> {6}|>, <|{3, "p"} -> {15}|>}

to

 {1, 1} -> {<|{2, "p"} -> {6,10}|>, <|{3, "p"} -> {15}|>}

as part of the original assoc.

Using

assoc[{1, 1}][[1]][{2, "p"}] caused errors.
$\endgroup$
7
  • 2
    $\begingroup$ AppendTo[assoc[[Key[{1,1}], 1, Key[{2, "p"}]]], 10]? $\endgroup$
    – Lukas Lang
    Dec 12, 2022 at 11:38
  • $\begingroup$ If I do assoc = AppendTo[assoc[[Key[{1,1}], 1, Key[{2, "p"}]]], 10] I see only {6,10}. - The question is about updating the entire structure, named assoc. But thanks for thinking along. $\endgroup$ Dec 12, 2022 at 11:47
  • 2
    $\begingroup$ @niloderoock it returns {6, 10} only but take a look at assoc, and drop assoc = part first. $\endgroup$
    – Kuba
    Dec 12, 2022 at 12:12
  • 1
    $\begingroup$ There is, but what is the point? assoc[[Key@{1, 1}, 1, Key@{2, "p"}]] = Append[ assoc[[Key@{1, 1}, 1, Key@{2, "p"}]], 10 ] $\endgroup$
    – Kuba
    Dec 12, 2022 at 12:47
  • 1
    $\begingroup$ The Append version that leaves assoc itself unmodified would be: MapAt[Append[10], assoc, {Key[{1, 1}], 1, Key[{2, "p"}]}] $\endgroup$ Dec 12, 2022 at 15:46

1 Answer 1

1
$\begingroup$

You can update the association with AssociateTo

AssociateTo[
  assoc, {{1, 1} -> {<|{2, "p"} -> {6, 10}|>, <|{3, "p"} -> {15}|>}}];

Which, like AppendTo updates the values stored in assoc.

assoc

<|{0} -> {1}, {1} -> {2, 3, 5, 7}, {2} -> {4, 9}, {1, 1} -> {<|{2, "p"} -> {6, 10}|>, <|{3, "p"} -> {15}|>}, {3} -> {8}|>

$\endgroup$
1
  • $\begingroup$ Look in the comments for the answer found by Kuba @Kuba . $\endgroup$ Dec 14, 2022 at 3:43

Your Answer

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

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