3
$\begingroup$

Saying we have an association:

asc = <|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>|>;

I want to updated values of "A". I have tried doing:

AssociateTo[
  asc, 
  asc["A"][#] -> If[asc["A"][#] === 1, 0 , asc["A"][#]] & /@ {"a", "b", "c"}]

<|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>, 1 -> 0, 2 -> 2, 3 -> 3|>

But this just adds valuesst to the association instead of adding to "A"

How can I update the values in "A" using AssociateTo?

$\endgroup$
5
$\begingroup$

One possibility would be the simple

asc["A"]["a"] = 99;

enter image description here

As @m_goldberg commented this can be shortened to

asc["A", "a"] = 99;

To change several keys:

asc[[1]][[2 ;; 3]] = 4

enter image description here

$\endgroup$
  • $\begingroup$ I need to that using AssociateTo $\endgroup$ – SuTron Nov 13 '15 at 12:51
  • $\begingroup$ +1, but I would use asc["A", "a"] = 99; $\endgroup$ – m_goldberg Nov 13 '15 at 16:43
  • $\begingroup$ Thanks @ Mr. Goldberg - that's a nice form - will update $\endgroup$ – eldo Nov 13 '15 at 16:46
0
$\begingroup$

I have came up with a solution:

In[1]:= asc = <|"A" -> <|"a" -> 1, "b" -> 2, "c" -> 3|>|>;
Module[{tmp = asc["A"]},
 AssociateTo[tmp, # -> tmp[#] + 1 & /@ {"a"}];
 AssociateTo[asc, "A" -> tmp]
 ]

Out[2]= <|"A" -> <|"a" -> 2, "b" -> 2, "c" -> 3|>|>
$\endgroup$
  • 1
    $\begingroup$ Why do you have to use AssocTo? It is a very poor tool for solving your problem. The simple expression asc["A", "a"] = asc["A", "a"] + 1; is much better. $\endgroup$ – m_goldberg Nov 13 '15 at 16:41
  • $\begingroup$ The question asks how to do that using AssociateTo[]. For complicated and nested associations it's a better fit to apply changes, when you need to do additional checks on keys. $\endgroup$ – SuTron Nov 20 '15 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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