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$
2
  • $\begingroup$ Closely related question $\endgroup$ Commented Nov 13, 2015 at 12:52
  • $\begingroup$ Possibly related? (79686) $\endgroup$
    – Mr.Wizard
    Commented Nov 13, 2015 at 13:37

2 Answers 2

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$
3
  • $\begingroup$ I need to that using AssociateTo $\endgroup$
    – SuTron
    Commented Nov 13, 2015 at 12:51
  • $\begingroup$ +1, but I would use asc["A", "a"] = 99; $\endgroup$
    – m_goldberg
    Commented Nov 13, 2015 at 16:43
  • $\begingroup$ Thanks @ Mr. Goldberg - that's a nice form - will update $\endgroup$
    – eldo
    Commented Nov 13, 2015 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$
2
  • 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
    Commented Nov 13, 2015 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
    Commented Nov 20, 2015 at 13:18

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.