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 PositionIndex
or Normal
or Keys
?
a[[2, ?]] == w
Query
is the best fit. Something likeQuery[2, Keys /* {1}]@a
$\endgroup$Part
syntax.Part
can only extract values. You can use keys asPart
specifications, but you will always get values out. $\endgroup$a // PositionIndex[#[[2]]][[1]] &
? $\endgroup$Association
s are atomic objects and are not even meant to be accessed withPart
in the traditional sense. In my interpretation,Part
was specially overloaded forAssociation
. $\endgroup$First @ Keys @ a[[2, {1}]]
, where the heavy lifting is still done byPart
. 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 ofQuery
. $\endgroup$