Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure get map key by value

Tags:

clojure

I'm a new clojure programmer.

Given...

{:foo "bar"}

Is there a way to retrieve the name of the key with a value "bar"?

I've looked through the map docs and can see a way to retrieve key and value or just value but not just the key. Help appreciated!

like image 408
Calvin Froedge Avatar asked Aug 11 '13 20:08

Calvin Froedge


1 Answers

There can be multiple key/value pairs with value "bar". The values are not hashed for lookup, contrarily to their keys. Depending on what you want to achieve, you can look up the key with a linear algorithm like:

(def hm {:foo "bar"})
(keep #(when (= (val %) "bar")
          (key %)) hm)

Or

(filter (comp #{"bar"} hm) (keys hm))

Or

(reduce-kv (fn [acc k v]
             (if (= v "bar")
               (conj acc k)
               acc))
           #{} hm)

which will return a seq of keys. If you know that your vals are distinct from each other, you can also create a reverse-lookup hash-map with

(clojure.set/map-invert hm)
like image 96
Leon Grapenthin Avatar answered Sep 23 '22 19:09

Leon Grapenthin