Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse lookup in a map

I have to extract a key from a map using a value. Is there a way to do this other than implementing reverse lookup myself?

like image 567
Isuru Avatar asked May 16 '12 04:05

Isuru


2 Answers

I think that map-invert is the right way to do this.

From the docs:

;; Despite being in clojure.set, this has nothing to do with sets. 

user=> (map-invert {:a 1, :b 2})
{2 :b, 1 :a}

;; If there are duplicate keys, one is chosen:

user=> (map-invert {:a 1, :b 1})
{1 :b}

;; I suspect it'd be unwise to depend on which key survives the clash.
like image 96
Eric Wilson Avatar answered Nov 16 '22 04:11

Eric Wilson


You can reverse a map really easily with a 2-line function:

(defn reverse-map [m]
  (into {} (map (fn [[a b]] [b a]) m)))

(def a {:a 1 :b 2 :c 3})

(reverse-map a)
=> {1 :a, 3 :c, 2 :b}

((reverse-map a) 1)
=> :a
like image 38
mikera Avatar answered Nov 16 '22 02:11

mikera