Reputation: 2372
I have the following data structure:
["a 1" "b 2" "c 3"]
How can I transform that into a hash-map?
I want the following data structure:
{:a 1 :b 2 :c 3}
Upvotes: 0
Views: 815
Reputation: 9865
(def x ["a 1" "b 2" "c 3"])
(clojure.edn/read-string (str "{:" (clojure.string/join " :" x) "}"))
;;=> {:a 1, :b 2, :c 3}
Upvotes: 0
Reputation: 17859
and one more :)
(->> ["a 1" "b 2" "c 3"]
(clojure.pprint/cl-format nil "{~{:~a ~}}")
clojure.edn/read-string)
;;=> {:a 1, :b 2, :c 3}
Upvotes: 3
Reputation: 4901
(into {}
(map #(clojure.edn/read-string (str "[:" % "]")))
["a 1" "b 2" "c 3"])
;; => {:a 1, :b 2, :c 3}
Upvotes: 0
Reputation: 7568
Use clojure.string/split
and then use keyword
and Integer/parseInt
:
(->> ["a 1" "b 2" "c 3"]
(map #(clojure.string/split % #" "))
(map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
(into {}))
=> {:a 1, :b 2, :c 3}
Upvotes: 6