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}}
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. $\endgroup$-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 $\endgroup${1,0,0,0}
etc haveSymbol
asHead
$\endgroup$