Group Abstract Group Abstract

Message Boards Message Boards

1
|
3.6K Views
|
4 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Accessing associations with [[ ]] and [ ]

Attachments:
POSTED BY: Henrick Jeanty
4 Replies
Posted 4 years ago

Hi Gianluca,

Take a look at this thread on MSE. I don't ever use Part with Association because it's behavior is not intuitive, at least to me.

Association[a -> b][[1]] (* Your example *)
(* b *)

Association[a -> b][[1 ;; 1]]
(* <|a -> b|> *)

Association[a -> b][[{1}]]
(* <|a -> b|> *)
POSTED BY: Rohit Namjoshi

I grew up with the principle "everything is an expression" in WL. Then I met Associations and the world crumbled. I was used to this behaviour:

In[58]:= f[a -> b]
%[[1]]

Out[58]= f[a -> b]

Out[59]= a -> b

Now I get this

In[54]:= Association[a -> b]
%[[1]]

Out[54]= <|a -> b|>

Out[55]= b
POSTED BY: Gianluca Gorni

Thank you so much Rohit. You helped me notice something that somehow I had missed. Towards the end of the example in the documentation they use the Part approach and I guess my mind got stuck on it, I was simply surprised when I noticed that the [ ] worked, and frankly, I prefer it.

Again, thank you for clarifying this for me. Now off to my code to replace all those uses of [[ ]] with [ ] when used with associations!

POSTED BY: Henrick Jeanty
Posted 4 years ago

Take a look at the Basic Examples section in the documentation for Association. You can use either, [[ ]] is syntax for Part. Better to avoid using the Part syntax with Association

a2 = AssociateTo[a, b -> c] (* Note b is not a String *)
(* <|"a" -> x, "b" -> y, "c" -> z, b -> c|> *)

a2[b]
(* c *)

a2["b"]
(* y *)

a2[[b]]
(* Part::pkspec1: The expression b cannot be used as a part specification. *)
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard