leifericf
leifericf

Reputation: 2372

Convert vector of strings into hash-map in Clojure

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

Answers (4)

Gwang-Jin Kim
Gwang-Jin Kim

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

leetwinski
leetwinski

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

Rulle
Rulle

Reputation: 4901

(into {}
      (map #(clojure.edn/read-string (str "[:" % "]")))
      ["a 1" "b 2" "c 3"])
;; => {:a 1, :b 2, :c 3}

Upvotes: 0

Martin Půda
Martin Půda

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

Related Questions