JoelKuiper
JoelKuiper

Reputation: 4710

Convert map of list into list of maps (i.e. rows to colums)

I have the following data structure in Clojure

{:a [1 2 3]
 :b [4 5 6]
 :c [7 8 9]} 

And I'd like to convert it into something like

[{:a 1 :b 4 :c 7}
 {:a 2 :b 5 :c 8}
 {:a 3 :b 6 :c 9}]

At the moment I'm kinda stumped as to how to do this.

Upvotes: 2

Views: 188

Answers (2)

NielsK
NielsK

Reputation: 6956

In Clojure you can never guarantee the order of keys in maps after transformations. They're indexed by key, not by order.

Vectors are, however. And with get-in you can do a lookup on position with a vector of coordinates .

=> (def mat
     [[1 2 3]
      [4 5 6]
      [7 8 9]])

=> (defn transpose
     [m]
     (apply mapv vector m))

=> (get-in (transpose mat) [1 2])
8

Upvotes: 3

JoelKuiper
JoelKuiper

Reputation: 4710

Got it:

(defn transpose-lists [x] 
  (map (fn [m] (zipmap (keys x) m)) (apply map vector (vals x))))

Unfortunately it doesn't preserve order of the keys. If anyone has a better solution then of course I'd like to hear it!

Upvotes: 2

Related Questions