Search code examples
clojure

swap keys and values in a map


Is there a function to swap the key and value of a given map. So given a map, I want the keys to become values, and values the keys.

(swap {:a 2 b 4}) => {2 :a 4 :b}

One way to do it is

(zipmap (vals my-map) (keys my-map))

However wondering if clojure provides a utility fn for this?


Solution

  • This is the purpose of map-invert in clojure.set:

    user=> (clojure.set/map-invert {:a 2 :b 4})
    {4 :b, 2 :a}