Skip to content

clojure.set/map-invert

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 3 Runnable: 0
([m])

Returns the map with the vals mapped to the keys.

Examples

by Brian Marick on . May have evaluation errors.
by bruno-oliveira on . May have evaluation errors.
by reborg on . May have evaluation errors.

Note by optevo

If you have the possibility of duplicate values, in your map, the invert-map function will only preserve one of them. An alternative which doesn't eliminate values is to ensure all values are sets then use the following function:

(defn invert-map-of-sets [m]
   (reduce (fn [a [k v]] (assoc a k (conj (get a k #{}) v))) {} (for [[k s] m v s] [v k]))))

This will work as follows:

;; From
{1 #{:a :b :c} 2 #{:b :c :d}}
;; To
{:c #{1 2}, :b #{1 2}, :a #{1}, :d #{2}}

Content from the matching ClojureDocs page, with authors credited on each contribution.