clojure.core/select-keys¶
Returns a map containing only those entries in map whose key is in keys
Examples¶
Note by gknapp¶
Why does select-keys return a map with keys in reverse order of the keyseq vector?
Jay Fields has a good blog post on select-keys with implementations of select-values (which is what I was really after).
Note by TheSeldonPlan¶
I think @gknapp is correct. select-keys returns a map with keys in the order of the keyseq vector. Perhaps this has changed since his comment, and the documentation needs to be updated.
user=> (select-keys {:a 1 :b 2 :c 3} [:a :c])
{:a 1, :c 3}
user=> (select-keys {:a 1 :b 2 :c 3} [:c :a])
{:c 3, :a 1}
Note by mlanza¶
Wouldn't the following signature be better for partial application?
(select-keys keyseq map)
(def stooges [{:name "Larry" :birthday "Oct 05"}
{:name "Curly" :birthday "Jun 19"}
{:name "Moe" :birthday "Oct 22"}])
Tacit style is about consistent order (general to specific), not concision:
(map (partial select-keys [:name]) stooges) ;tacit
(map #(select-keys % [:name]) stooges)
Note by raszi¶
If you are looking for a select-vals or select-values alternative of this function, you can do the following:
(map {:a 1 :b 2 :c 3 :d 4} [:a :d])
;;=> (1 4)
Note by hkjels¶
select-keys will return in the order provided for array-maps. However, array-maps turn into hash-maps at a certain threshold, which are un-ordered. So generally, when you need certain ordering, use a sequence instead.
Note by didibus¶
VERY IMPORTANT!!!
select-keys returns a map. Maps DO NOT guarantee ordering of their key/value pairs. If you depend on order, do not rely on select-keys.
You might think the order is preserved, only because maps of 8 elements or less in Clojure are implemented with an array-map which preserves insertion order, but maps beyond that will use a hash-map which does not guarantee ordering. And this is an implementation details, in future release of Clojure, the threshold or type of implementation for maps could change to any other which could even break the ordering for small maps.
See also¶
- clojure.core/get (8)
- clojure.core/keys (2)
- clojure.core/dissoc (3)
- clojure.core/hash-map (3)
Content from the matching ClojureDocs page, with authors credited on each contribution.