# How to swap keys and values of an association? [duplicate]

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: 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]]


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

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


• 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. Nov 22, 2021 at 13:54
• I explain what I am trying to do within the body of the question. Nov 22, 2021 at 22:37

## 2 Answers

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.

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