Search code examples
clojure

Clojure get map key by value


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!


Solution

  • 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)