Taking the first element in a list of associations
You can use the fact that Part
([[…]]
) preserves the keys when you supply a list of indices to extract:
z[[All, {1}]]
(* {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} ->
6|>, <|{"s", "t"} -> 10|>} *)
(* without the list *)
z[[All, 1]]
(* {1, 4, 6, 10} *)
Alternatively you could use Take
:
Map[Take[#, 1] &, z]
(* {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} ->
6|>, <|{"s", "t"} -> 10|>} *)
Other possibilites:
Map[#[[{1}]] &, z]
(* {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} ->
6|>, <|{"s", "t"} -> 10|>} *)
z[[All, ;; 1]]
(* {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} ->
6|>, <|{"s", "t"} -> 10|>} *)
In essence, anything that could in principle return multiple elements will preserve the keys (or, more generally, will preserve that level of the nested expression)
For completeness sake, a few more:
Extract[z, {All, {1}}]
(* {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} ->
6|>, <|{"s", "t"} -> 10|>} *)
Cases[z, KeyValuePattern[{x_ -> y_}] :> x -> y]
(*{{"a", "b"} -> 1, {"g", "h"} -> 4, {"k", "l"} -> 6, {"s", "t"} -> 10}*)