6
$\begingroup$
as = <|1 -> 2.2, 2 -> 3.4, 3 -> 8.1|>;

I don't understand the following:

as[[1]]

2.2

But I expected to see

<|1 -> 2.2|>

On the other hand:

as[[1 ;; 1]]

<|1 -> 2.2|>

$\endgroup$
  • 3
    $\begingroup$ It;s like as[[{1}]] and if you have other head than association, it will be kept too. $\endgroup$ – Kuba Nov 3 '15 at 20:07
  • 2
    $\begingroup$ When you do list[[1]] you don't expect to get a list so why do you expect association[[1]] to give an association? $\endgroup$ – Simon Woods Nov 3 '15 at 20:31
  • $\begingroup$ Right, but one could expect 1->2.2 $\endgroup$ – eldo Nov 3 '15 at 20:38
  • 2
    $\begingroup$ An association is not a list of rules. It's a different animal. Your intuition is correct if you do it on Normal[as]. $\endgroup$ – Philip Maymin Nov 3 '15 at 21:56
7
$\begingroup$

Probably should be handled by KeyTake:

KeyTake[as, 1]

<|1->2.2|>

Also works with multiple "selections":

KeyTake[as, {1, 3}]

<|1 -> 2.2, 3 -> 8.1|>

$\endgroup$
6
$\begingroup$

The difference could be related to the fact that Part (as[[1]]) treats associations transparently while as[[1;;1]] (i.e. as[[1~Span~1]]) is equivalent to Take[as[1,1]], and Take does not treat associations transparently.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.