I have an association dataset with a depth of two (each value is an association too, and the size of the dataset ~ 30000 keys and an average size of values are ~2000 keys association). The dataset looks like:

  dataset=<| 2 -> <|3 -> 3, 5 -> 4|>,4 -> <|5 -> 15|>, 5 -> <|1 -> 41, 2 -> 
   4,3 -> 10, 4 -> 11|>|>

I need to change specific values in this dataset. I do it in the following manner:

dataset= 
 ReplacePart[
   dataset, {Key@23980, Key@19969} -> {5, 
  6}]; // AbsoluteTiming

  {0.000110522, Null}

This operation takes a lot of time for my dataset, around 110 msec. I repeat this procedure thousands of times, so it is a real bottleneck for my program.

Any suggestions on how to speed up this procedure?

Here is a working example:

dataset = <|2 -> <|3 -> 3, 5 -> 4|>, 4 -> <|5 -> 15|>, 5 -> <|1 -> 41, 2 -> 4, 3 -> 10, 4 -> 11|>|>;
dataset = ReplacePart[dataset, {Key@4, Key@5} -> {5, 6}]
(* <|2 -> <|3 -> 3, 5 -> 4|>, 4 -> <|5 -> 15|>, 5 -> <|1 -> 41, 2 -> 4, 3 -> 10, 4 -> 11|>|> *)
(* <|2 -> <|3 -> 3, 5 -> 4|>, 4 -> <|5 -> {5, 6}|>, 5 -> <|1 -> 41, 2 -> 4, 3 -> 10, 4 -> 11|>|> *)
  • Can't you just do: dataset[4, 5] = {5,6}? – Carl Woll Jun 13 at 6:34
  • Thank you! Yes, so simple so quick, this approach sped up by factor 10. Can you change your comment to answer, please? – Kiril Danilchenko Jun 13 at 6:44
  • My answer was extra-useless as I wasn't realizing what you are doing. @CarlWoll Are you posting an answer? – halirutan Jun 13 at 6:49
up vote 7 down vote accepted

As the last basic example for Association says:

Associations can be modified by resetting values:

assoc=<|a->x,b->y,c->z|>

<|a -> x, b -> y, c -> z|>

assoc[b]=w

w

assoc

<|a -> x, b -> w, c -> z|>

So, you can just set the values directly using:

dataset = <|
    2 -> <|3 -> 3, 5 -> 4|>,
    4 -> <|5 -> 15|>,
    5 -> <|1 -> 41, 2 -> 4,  3 -> 10, 4 -> 11|>
|>;
dataset[4, 5] = {5, 6};

dataset

<|2 -> <|3 -> 3, 5 -> 4|>, 4 -> <|5 -> {5, 6}|>, 5 -> <|1 -> 41, 2 -> 4, 3 -> 10, 4 -> 11|>|>

Notice that 4, 5 has been reset from 15 to {5, 6}.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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