Select keys to form a tupled map in Clojure

cbillowes

Clarice Bouwer

Posted on January 17, 2023

Select keys to form a tupled map in Clojure

Example:

Taking a vector of maps that looks like

[{:fruit "apple" :color "red" :brand "Granny Smith"}
 {:fruit "banana" :color "yellow" :brand "Banana shop"}]
Enter fullscreen mode Exit fullscreen mode

and converting it into {:fruit :color}

({"apple" "red"} {"banana" "yellow"})
Enter fullscreen mode Exit fullscreen mode

Create a hash map from an even list of data

(defn create-hash-map [data] (apply hash-map data))
Enter fullscreen mode Exit fullscreen mode

Output

:> (create-hash-map [1 2 3 4 5 6])
{1 2, 3 4, 5 6}

:> (create-hash-map [1 2 3 4 5])
; Execution error (IllegalArgumentException) at ns/create-hash-map (REPL:31).
; No value supplied for key: 5
Enter fullscreen mode Exit fullscreen mode

Extract a key and value from a map to form a tupled map

(defn tuple [key value data]
  (-> data
      (select-keys [key value])
      (vals)
      (create-hash-map)))
Enter fullscreen mode Exit fullscreen mode

Output

:> (tuple :fruit :color {:fruit "apple" :color "red" :brand "Granny Smith"})
{"apple" "red"}
Enter fullscreen mode Exit fullscreen mode

Map through a list of maps to create tuples for each item.

 (map
  #(tuple :fruit :color %)
  [{:fruit "apple" :color "red" :brand "Granny Smith"}
   {:fruit "banana" :color "yellow" :brand "South African Bananas"}])
Enter fullscreen mode Exit fullscreen mode

Output

({"apple" "red"} {"banana" "yellow"})
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
cbillowes
Clarice Bouwer

Posted on January 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related