8
$\begingroup$

I have the following list which is built up of associations, that is,

z = {<|{"a", "b"} -> 1, {"c", "d"} -> 2, {"e", "f"} -> 
    3|>, <|{"g", "h"} -> 4, {"i", "j"} -> 5|>, <|{"k", "l"} -> 
    6, {"m", "n"} -> 7, {"o", "p"} -> 8, {"q", "r"} -> 
    9|>, <|{"s", "t"} -> 10|>}

I am trying to to pick the first elements in each association such that it gives:

 {<|{"a", "b"} -> 1|>, <|{"g", "h"} -> 4|>, <|{"k", "l"} -> 
 6|>, <|{"s", "t"} -> 10|>}

to do that I do,

Map[First, z]

but this only returns the values, how can one fix this?

$\endgroup$

2 Answers 2

11
$\begingroup$

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)

$\endgroup$
5
$\begingroup$

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}*)
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.