6
$\begingroup$

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|>|> *)
$\endgroup$
3
  • $\begingroup$ Can't you just do: dataset[4, 5] = {5,6}? $\endgroup$
    – Carl Woll
    Jun 13, 2018 at 6:34
  • $\begingroup$ Thank you! Yes, so simple so quick, this approach sped up by factor 10. Can you change your comment to answer, please? $\endgroup$ Jun 13, 2018 at 6:44
  • $\begingroup$ My answer was extra-useless as I wasn't realizing what you are doing. @CarlWoll Are you posting an answer? $\endgroup$
    – halirutan
    Jun 13, 2018 at 6:49

1 Answer 1

9
$\begingroup$

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}.

$\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.