Clojure get card key by value

I am a new clojure programmer.

Considering,...

{:foo "bar"} 

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

I looked at the map documents and see a way to get the key and value or just the value, but not just the key. Help rate!

+7
clojure
source share
2 answers

There may be several key / value pairs with a value of "bar". Values ​​are not hashed for search, opposite to their keys. Depending on what you want to achieve, you can find the key using a linear algorithm, for example:

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

or

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

or

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

which will return the keys section. If you know that your vals are different from each other, you can also create a hash map with reverse lookup using

 (clojure.set/map-invert hm) 
+18
source share
 user> (->> {:a "bar" :b "foo" :c "bar" :d "baz"} ; initial map (group-by val) ; sorted into a new map based on value of each key (#(get % "bar")) ; extract the entries that had value "bar" (map key)) ; get the keys that had value bar (:a :c) 
+5
source share

All Articles