1
$\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$
  • $\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 at 19:46
  • 3
    $\begingroup$ Lookup[{"a", "b"}] @ assoc $\endgroup$ – eldo Jan 25 at 20:10
  • $\begingroup$ Thanks, Nasser. I haven’t used them much myself. I find the syntax a bit confusing. $\endgroup$ – David Keith Jan 25 at 20:23
  • $\begingroup$ Thanks also, Elmo. That works great. $\endgroup$ – David Keith Jan 25 at 20:25
  • $\begingroup$ @eldo, please post that as an answer. :) I didn't know Lookup[] can thread across a list of associations! $\endgroup$ – J. M.'s discontentment Jan 26 at 12:02
3
$\begingroup$

Does this do what you want?

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

{{1, 2}, {4, 5}, {7, 8}}
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks, that’s great. $\endgroup$ – David Keith Jan 25 at 20:22
5
$\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}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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