12
$\begingroup$

I experienced a problem in changing values in an association and broke down the problem to the following: Given a list of association (here with one element):

temp = {<|"name" -> "Peter", "Punkte" -> 10, "Gender" -> "nn"|>}

then the following does not work:

temp[[1]]["Gender"] = "M"

but

assoc = temp[[1]]

and

assoc["Gender"] = "M"

works fine. I do not understand why?

$\endgroup$
1
  • $\begingroup$ I have covered exactly this case in this answer, towards the end of the section named "Complications". What works is temp[[1]][[Key["Gender"]]] = "M" (apart from suggestions from other answers, but I believe my suggestion is closer to your original attempt). $\endgroup$ Commented Jan 29, 2015 at 13:07

1 Answer 1

15
$\begingroup$

When you try temp[[1]]["Gender"] = "M" you get a warning message:

Association::setps: <|name->Peter,Punkte->10,Gender->nn|> in the part assignment is not a symbol. >>

This is telling you that the syntax assoc[key] = value is only valid if assoc is a symbol. You get the same warning if you try <|a -> 1|>[a] = 2

The simplest solution is to use the Part syntax for changing the value:

temp[[1, "Gender"]] = "M"
(* "M" *)

temp   
(* {<|"name" -> "Peter", "Punkte" -> 10, "Gender" -> "M"|>}
$\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.