Getting keys of an 'Association'

Suppose you have an association of the type:

a = {1, 0, 0, 0}; b = {0, 1, 0, 0}; c = {0, 0, 1, 0}; d = {0, 0, 0, 1}; e = {2, 0, 0, 0};
f = {0, 2, 0, 0}; g = {0, 0, 2, 0}; h = {0, 0,0, 2};
assoc = Association[1 -> a, 2 -> b, 3 -> c, 4 -> d, 5 -> e, 6 -> f, 7 -> g, 8 -> h]

(*=> <|1 -> {1, 0, 0, 0}, 2 -> {0, 1, 0, 0}, 3 -> {0, 0, 1, 0}, 4 -> {0, 0, 0, 1},
5 -> {2, 0, 0, 0}, 6 -> {0, 2, 0, 0}, 7 -> {0, 0, 2, 0}, 8 -> {0, 0, 0, 2}|> *)


In general, the association may contain many more terms. You can access the keys, given the values using PositionIndex, e.g.:

PositionIndex[assoc][{2, 0, 0, 0}]
(*=> {5} *)


Suppose the output of a calculation is of the form:

-0.2*{0, 1, 0, 0} + 0.4*{2, 0, 0, 0} + 0.11*{0, 0, 2, 0} + 0.7*{0, 0, 1, 0}


How can you get a list of pairs where the pair consists of the coefficient and the corresponding key of the element of assoc? I.e., for the above output, how can you create the following list?

{{-0.2, 2}, {0.4, 5}, {0.11, 7}, {0.7,3}}

• You could start by turning the association around: assoc2 = Association@KeyValueMap[#2 -> #1 &, assoc] gives <|{1, 0, 0, 0} -> 1, {0, 1, 0, 0} -> 2, {0, 0, 1, 0} -> 3, {0, 0, 0, 1} -> 4, {2, 0, 0, 0} -> 5, {0, 2, 0, 0} -> 6, {0, 0, 2, 0} -> 7, {0, 0, 0, 2} -> 8|>, which can then be used more easily to do what you want. Jan 26, 2021 at 9:43
• Also, -0.2*{0, 1, 0, 0} + 0.4*{2, 0, 0, 0} + 0.11*{0, 0, 2, 0} + 0.7*{0, 0, 1, 0} will be immediately evaluated to -0.2*{0, 1, 0, 0} + 0.4*{2, 0, 0, 0} + 0.11*{0, 0, 2, 0} + 0.7*{0, 0, 1, 0}, so that format is not ideal Jan 26, 2021 at 9:45
• You must have some code that assembles the output above. However, as @Hausdorff mentioned, the output will at once be simplified. Therefore, instead of assemble an output that looses information, assemble directly what you want: {{-0.2, 2}, {0.4, 5}... Jan 26, 2021 at 9:59
• Thanks for the comments. You are right. Suppose {1,0,0,0} etc have Symbol as Head
– geom
Jan 26, 2021 at 11:06

Normally, as @Hausdorff mentioned, you won't get -0.2*{0, 1, 0, 0} + 0.4*{2, 0, 0, 0} + 0.11*{0, 0, 2, 0} + 0.7*{0, 0, 1, 0} as output due to immediate evaluation. But if this is only a simplified example of yours and you're somehow able to preserve the elements in the output, try something like this:

assoc = Association[1 -> a, 2 -> b, 3 -> c, 4 -> d, 5 -> e, 6 -> f,
7 -> g, 8 -> h];
iassoc = GeneralUtilitiesAssociationInvert[assoc]
Cases[-0.2 b + 0.4*e - 0.11*g + 0.7*c, x_*y_ :> {x, iassoc[y]}]


{{-0.2, 2}, {0.7, 3}, {0.4, 5}, {-0.11, 7}}

(It's recommended you post your original data format so that more specific answers can be given!)

• Thanks for the answer. Cases[-0.2 b + 0.4*e - 0.11*g + 0.7*c, x_*y_ :> {x, iassoc[y]}]` was the line I needed.
– geom
Jan 26, 2021 at 11:04