0

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}

2
  • 1
    Please add the code you have tried and how it failed (e.g. errors, stacktraces, logs, ...) so we can improve on it. Commented Dec 2, 2021 at 10:15
  • 1
    @cfrick Thanks for you suggestion. I did not have any meaningful code or errors to show. As I'm brand new to Clojure, my attempts were futile and would not add any meaningful value to the question—It would only have cluttered up the question with unnecessary verbiage. I opted for succinctness, for ease of reading and to respect peoples' time. Commented Dec 2, 2021 at 11:37

4 Answers 4

6

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}
Sign up to request clarification or add additional context in comments.

Comments

3

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}

Comments

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

Comments

0
(def x ["a 1" "b 2" "c 3"])
(clojure.edn/read-string (str "{:" (clojure.string/join " :" x) "}"))
;;=> {:a 1, :b 2, :c 3}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.