Clojure get map key by value

前端 未结 3 1758
失恋的感觉
失恋的感觉 2020-12-31 11:58

I\'m a new clojure programmer.

Given...

{:foo \"bar\"}

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

相关标签:
3条回答
  • 2020-12-31 12:30
    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)
    
    0 讨论(0)
  • 2020-12-31 12:41

    As in many other cases you can use for:

    (def hm {:foo "bar"})
    (for [[k v] hm :when (= v "bar")] k)
    
    0 讨论(0)
  • 2020-12-31 12:50

    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)
    
    0 讨论(0)
提交回复
热议问题