5
$\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$
6
  • $\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$ Commented Jan 25, 2020 at 19:46
  • 7
    $\begingroup$ Lookup[{"a", "b"}] @ assoc $\endgroup$ Commented Jan 25, 2020 at 20:10
  • $\begingroup$ Thanks, Nasser. I haven’t used them much myself. I find the syntax a bit confusing. $\endgroup$ Commented Jan 25, 2020 at 20:23
  • $\begingroup$ Thanks also, Elmo. That works great. $\endgroup$ Commented 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$ Commented Jan 26, 2020 at 12:02

4 Answers 4

6
$\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$ Commented Jan 25, 2020 at 20:22
11
$\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$
3
$\begingroup$

Using Extract:

Map[Extract[#, {{"a"}, {"b"}}] &]@assoc 

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

Or using Merge and Extract:

Thread[Extract[Merge[assoc, Identity], {{"a"}, {"b"}}]] 

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

$\endgroup$
3
$\begingroup$

Also

{"a", "b"} /. assoc (* {{1, 2}, {4, 5}, {7, 8}} *) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.