Let's say I have the association

assoc = <|"random1" -> {a,b,c}, "random11" -> {b}|>

I want to replace the values, based on something related to the keys. For example, the values should be based on the number of digits in the corresponding key or the length of the key. If it's based on number of digits in the key, the final assoc would be:

assoc = <|"random1" -> {1}, "random11" -> {2}|>

If it's based on the stringlength then it would be:

assoc = <|"random1" -> {7}, "random11" -> {8}|>

How do I do this?

  • 2
    $\begingroup$ See KeyValueMap. Or if you want to build a new Association based purely on key values see AssociationMap and do AssociationMap[f,Keys[a]] $\endgroup$ – b3m2a1 Jun 11 '17 at 4:02
  • $\begingroup$ Thanks a lot. I was messing around with Keyvaluemap but I couldn't get it done. AssociationMap did what I wanted. $\endgroup$ – whoami Jun 11 '17 at 4:10

As posted in the comments by b3m2a1, replacing the values with length of keys for example can be achieved by:

AssociationMap[StringLength, Keys[assoc]]

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.