2
$\begingroup$

I have data stored in a list of Associations. I would like to extract the values only for multiple keys. I was hoping to do it the same way list[[All,{1,2}]] can be used. But when I use this syntax with Associations I extract Key-value pairs instead of values. Is their a terse syntax for what I want?

assoc = {
   <|"a" -> 1, "b" -> 2, "c" -> 3|>,
   <|"a" -> 4, "b" -> 5, "c" -> 6|>,
   <|"a" -> 7, "b" -> 8, "c" -> 9|>
   };

assoc[[All, "a"]]

(* {1,4,7} *)

assoc[[All, {"a", "b"}]]

{<|"a" -> 1, "b" -> 2|>, <|"a" -> 4, "b" -> 5|>, <|"a" -> 7, 
  "b" -> 8|>} 
$\endgroup$
5
  • $\begingroup$ Is their a terse syntax for what I want? I do not know. I do not use associations much. But you could always use mapping I suppose: assoc[[All, #]] & /@ {"a", "b"} $\endgroup$
    – Nasser
    Jan 25, 2020 at 19:46
  • 3
    $\begingroup$ Lookup[{"a", "b"}] @ assoc $\endgroup$
    – eldo
    Jan 25, 2020 at 20:10
  • $\begingroup$ Thanks, Nasser. I haven’t used them much myself. I find the syntax a bit confusing. $\endgroup$ Jan 25, 2020 at 20:23
  • $\begingroup$ Thanks also, Elmo. That works great. $\endgroup$ Jan 25, 2020 at 20:25
  • $\begingroup$ @eldo, please post that as an answer. :) I didn't know Lookup[] can thread across a list of associations! $\endgroup$ Jan 26, 2020 at 12:02

2 Answers 2

4
$\begingroup$

Does this do what you want?

Values[assoc[[All, {"a", "b"}]]]

{{1, 2}, {4, 5}, {7, 8}}
$\endgroup$
1
  • $\begingroup$ Thanks, that’s great. $\endgroup$ Jan 25, 2020 at 20:22
6
$\begingroup$

Upon request I post my comment as an answer.

The documentation states under examples:

Lookup threads over lists of associations:

Lookup[{"a", "b"}] @ assoc

{{1, 2}, {4, 5}, {7, 8}}

$\endgroup$

Your Answer

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

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