4
$\begingroup$

I have some large nested expression containing associations and I'd like to extract the nth key inside one of them, using part syntax.

Here's a tiny example:

a = {1, <|w->x, b->{y,z}|>};

I'd like to extract the first key using part syntax, is it even possible without using functions like Query or PositionIndexor Normal or Keys?

a[[2, ?]] == w
$\endgroup$
6
  • 4
    $\begingroup$ I think Query is the best fit. Something like Query[2, Keys /* {1}]@a $\endgroup$
    – Edmund
    Nov 10, 2017 at 0:50
  • 6
    $\begingroup$ As a short answer: no, you cannot extract keys using Part syntax. Part can only extract values. You can use keys as Part specifications, but you will always get values out. $\endgroup$ Nov 10, 2017 at 9:38
  • 1
    $\begingroup$ Maybe a // PositionIndex[#[[2]]][[1]] & ? $\endgroup$
    – user1066
    Nov 10, 2017 at 10:06
  • 3
    $\begingroup$ To put it more bluntly than Sjoerd: Associations are atomic objects and are not even meant to be accessed with Part in the traditional sense. In my interpretation, Part was specially overloaded for Association. $\endgroup$
    – LLlAMnYP
    Nov 10, 2017 at 12:02
  • 4
    $\begingroup$ You can do this as First @ Keys @ a[[2, {1}]], where the heavy lifting is still done by Part. By wrapping the last position in a List, we tell the Part that we want to preserve the head, which is an assoc, so you get back <|w -> x|>. This should generalize to any other such case you want. This is similar to the suggestion of @Edmund, except that we don't have the overhead of Query. $\endgroup$ Nov 10, 2017 at 13:37

0

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.

Browse other questions tagged or ask your own question.