zipmap

added
1.0

ns
clojure.core

type
function

(zipmap keys vals)

Returns a map with the keys mapped to the corresponding vals.

                user=> (zipmap [:a :b :c :d :e] [1 2 3 4 5])
{:a 1, :b 2, :c 3, :d 4, :e 5}

            
                ;; 4 is not included in the result
user=> (zipmap [:a :b :c] [1 2 3 4])
{:a 1, :b 2, :c 3}

;; :c is not included in the result
user=> (zipmap [:a :b :c] [1 2])
{:a 1, :b 2}
            
                user=> (pprint 
         (zipmap [:html :body :div] (repeat {:margin 0 :padding 0})))
{:html {:margin 0, :padding 0},
 :body {:margin 0, :padding 0},
 :div {:margin 0, :padding 0}}
            
                ;; transform a CSV file to an array of maps using the header line as keys
user=> (defn csv-map
  "ZipMaps header as keys and values from lines."
  [head & lines]
    (map #(zipmap (map keyword head) %1) lines))

user=> (apply csv-map [["FirstName", "LastName"], ["John", "Doe"], ["Jill", "Doh"]])
({:FirstName "John", :LastName "Doe"}, {:FirstName "Jill", :LastName "Doh"})
            
                ;; initialize with 0 for all values
user=> (zipmap [:a :b :c] (repeat 0))
{:a 0, :b 0, :c 0}
            
                ;; Note that if the keys are not unique, you can potentially lose data:
user=> (zipmap [:a :b :c :a] [1 2 3 4])
{:a 4, :b 2, :c 3}