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$
4
  • 3
    $\begingroup$ It;s like as[[{1}]] and if you have other head than association, it will be kept too. $\endgroup$
    – Kuba
    Nov 3, 2015 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$ Nov 3, 2015 at 20:31
  • $\begingroup$ Right, but one could expect 1->2.2 $\endgroup$
    – eldo
    Nov 3, 2015 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$ Nov 3, 2015 at 21:56

2 Answers 2

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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