1
$\begingroup$

How do you swap the values and keys of an Association in a manner similar to taking the transpose of a two-dimensional matrix or nested list? I am trying to solve the Wolfram Challenge Capital Cities Near a Latitude I created an association of data with the capital of each country as the key and the difference between a specific latitude (I chose 38° in this example, but any value can be used by replacing it with a function's parameter variable) as follows:

data = AssociationMap[Abs[QuantityMagnitude@#["Latitude"] - 38] &, 
  DeleteMissing@EntityValue["Country", "CapitalCity"]]

I then sort the data in ascending order:

Sort[data]

My next goal was to extract my goal of Athens as the answer: enter image description here Part does not work because it returns the value referring to the latitude difference, not the key referring to the capital city:

Sort[data][[1]]

enter image description here

The way I found was roundabout, prompting me to think if there is a better way:

(Keys@Take[Sort[data], 1])[[1]]

enter image description here

$\endgroup$
2
  • 2
    $\begingroup$ This may be a dangerous proposition if your keys and values are not all distinct among them. I suspect that there might be another solution to the problem you are trying to solve in this way: tell us more about the context in which this problem arose for you. $\endgroup$
    – MarcoB
    Nov 22, 2021 at 13:54
  • $\begingroup$ I explain what I am trying to do within the body of the question. $\endgroup$ Nov 22, 2021 at 22:37

2 Answers 2

3
$\begingroup$

I suppose AssociationThread[Values@assoc, Keys@assoc], but it's not invertible if the values are not distinct.

Also Association@KeyValueMap[#2 -> #1 &, assoc] with the same caveat.

$\endgroup$
1
$\begingroup$
TakeSmallest[data, 1]
(* <|Entity["City", {"Athens", "Attiki", "Greece"}] -> 0.02|> *)
$\endgroup$

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