Group Abstract Group Abstract

Message Boards Message Boards

0
|
53 Views
|
4 Replies
|
1 Total Like
View groups...
Share
Share this post:
GROUPS:

How to lookup a list in an association?

Posted 23 hours ago

Hi, suppose I have an association

assoc = <|{1, 2} -> 1, {2, 3} -> 2|>

and I want to lookup the value of {1, 2} in assoc, then what is the best way to do it? It is not

Lookup[assoc, {1, 2}]

since that threads the Lookup over {1, 2} and returns {Missing["KeyAbsent", 1], Missing["KeyAbsent", 2]}. Is this an unintended bug? I guess it would be more appropriate if Mathematica didn't thread Lookup over lists...

POSTED BY: Naman Taggar
4 Replies
Posted 19 hours ago

I think the confusion comes from the fact that Lookup treats a list of keys as multiple keys to retrieve, rather than treating the whole list as a single key.

For this kind of association, using Key[{1, 2}] makes the intention explicit. Another option is to use assoc[{1, 2}] if you want to access the key directly.

I would not necessarily call the behavior a bug, since Lookup is designed to accept a list when you want to retrieve several keys at once. It just becomes confusing when the keys themselves are lists.

POSTED BY: beenu ston
Posted 19 hours ago

Yes. Use of Key explains why Lookup behaves like that. I wasn't aware of Key, so I thought if a list is accepted as key in an association, why wouldn't Lookup be mindful of such keys! That's why I was confused.

POSTED BY: Naman Taggar
Posted 20 hours ago

Oh wonderful, thanks!

POSTED BY: Naman Taggar

We need Key when the key is not a string:

Lookup[assoc, Key[{1, 2}]]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard