6
$\begingroup$

Say I have a list of Association,

SeedRandom[45]
test = Association[Table[i -> RandomInteger[30], {i, 6}]]

<|1 -> 18, 2 -> 19, 3 -> 12, 4 -> 28, 5 -> 22, 6 -> 3|>

How to efficiently update the values according to new rules/counts? I tried

AssociateTo[test, -Counts[{2, 1, 2, 6}]]

<|1 -> -1, 2 -> -2, 3 -> 12, 4 -> 28, 5 -> 22, 6 -> -1|>

which is obvisoult not what I want. Desired result is

<|1 -> 17, 2 -> 17, 3 -> 12, 4 -> 28, 5 -> 22, 6 -> 2|>

That is, to reduce the value of relevant keys by the number of counts.

I used -Counts[] hope it add to the old values, but it was obviously the wrong thing to use here.

Apart from setting up long winded rules to locate each key and change its value individually, I am sure there are more efficient ways to hand this?

I have long Association and needs to update quickly (efficiently).

Thanks.

$\endgroup$

1 Answer 1

5
$\begingroup$

You are looking to merge your two associations. Use Merge, and use Total to combine the paired up values from the two associations to sum them:

Merge[{test, -Counts[{2, 1, 2, 6}]}, Total]

(* Out: <|1 -> 17, 2 -> 17, 3 -> 12, 4 -> 28, 5 -> 22, 6 -> 2|> *)

To check how this works, take a look at the result of the plain combination, i.e. Merge[{test, -Counts[{2, 1, 2, 6}]}, Identity].

$\endgroup$
2
  • $\begingroup$ I checked a lot of related syntax and I didn't see this! Thanks. It's exactly what I need! $\endgroup$ Jun 18, 2018 at 2:05
  • $\begingroup$ @ChenStatsYu Glad it helps! $\endgroup$
    – MarcoB
    Jun 18, 2018 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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