Group Abstract Group Abstract

Message Boards Message Boards

1
|
5.7K Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Lookup in an association when the keys are lists?

Posted 9 years ago

Hi everyone,

I have an Association in which the keys are lists. The first key might be

{20, a, b}

and the second key might be

{47, e, g}

and so on. How can I lookup or extract all values for which the first element in each key is, say, 20? I guess I'm looking for the Association equivalent of

Select[myTable,  #[[1]] == 20 &]

or

GatherBy[myTable, #[[1]]&]

Regards,

Gregory

POSTED BY: Gregory Lypny
3 Replies
Posted 9 years ago

Hi Christopher and Henrik, Thanks for your tips. They were a big help. Gregory

POSTED BY: Gregory Lypny

One simple approach might be to do key-selection outside of the Association framework like so:

testAssoc /@ Cases[Keys[testAssoc], {20, _, _}]

or likewise:

testAssoc[[Key /@ Cases[Keys[testAssoc], {20, _, _}]]]

Regards -- Henrik

POSTED BY: Henrik Schachner

You might be able to accomplish this with the new KeyValuePattern object in Mathematica 10.4. I've tried, though, and can't seem to figure out what function should then be used to actually apply the pattern to select matching key->value pairs from an association. I crafted a test association that is similar to yours, with keys that are lists, and was able to get MatchQ working with a KeyValuePattern such as:

MatchQ[testAssoc, KeyValuePattern[{{20, _, _} -> _}]]

That returned True, as it should, but I couldn't figure out how to actually return an association of key->value pairs that match the pattern.

POSTED BY: Christopher Fox
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard