Message Boards Message Boards

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

Accessing associations with [[ ]] and [ ]

I have a question about my understanding of Associations and referencing them. I've added the code with my question in it. Essentially, I have an association a which I dereference with: a[[ "a"]] (The key just happens to be the letter a) and that works. That is the way I understand one accesses data in an association when the key is a string, otherwise I have to use the keyword Key as in a[[ Key[some key] ]] Where I get confused is that the following also works: a["a"] and gives me the same result as a[["a"]]. Does that mean that I can also use [ ] (as in a function call) to access the data stored in an Association? Or, is there something I am not grasping?

Attachments:
POSTED BY: Henrick Jeanty
4 Replies
Posted 3 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

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

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
Posted 3 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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract