1
$\begingroup$

Consider an association

assoc := Association[{"a" -> 1, "b" -> 2} ]

How can I invert it, i.e., to obtain the following?

assocInvert:=Association[{1->"a",2->"b"}]
$\endgroup$
2

1 Answer 1

5
$\begingroup$
Association[KeyValueMap[Reverse@*Rule, assoc]]

or

Association[Reverse /@ Normal[assoc]]
$\endgroup$
2
  • 5
    $\begingroup$ The implementation of GeneralUtilities`AssociationInvert is, perhaps more simply, AssociationThread[Values[assoc], Keys[assoc]]. $\endgroup$
    – MarcoB
    May 5, 2023 at 21:47
  • $\begingroup$ @MarcoB excellent! why did you not make that an answer? $\endgroup$
    – lericr
    May 5, 2023 at 21:53

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