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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With