Association

Association[key1val1,key2val2,] or
represents an association between keys and values.

DetailsDetails

  • The value associated with a given key can be extracted using .
  • An Association acts like a symbolically indexed list. The value associated with a given key can be extracted by using the part specification Key[key]. If key is a string, Key can be omitted.
  • If key is not present in assoc, yields Missing["KeyAbsent",key].
  • Typical list operations (such as Map, Select, and Sort) apply to the values in an association, leaving the keys unchanged.
  • Association[{key1->val1,}] gives .
  • If there are multiple elements with the same key, all but the last of these elements are dropped. Merge yields instead a list of values for repeated keys.
  • Association can be input using the characters \[LeftAssociation] and \[RightAssociation].
  • Normal converts an Association to a list of rules.

ExamplesExamplesopen allclose all

Basic Examples  (8)Basic Examples  (8)

An association in which key is associated with value , key with value , etc.:

In[1]:=
Click for copyable input
Out[1]=

Extract the value associated with key :

In[2]:=
Click for copyable input
Out[2]=

Convert a list of rules to an association:

In[1]:=
Click for copyable input
Out[1]=

Convert an association to a list of rules:

In[2]:=
Click for copyable input
Out[2]=

Keys are "transparent" for many operations:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=
In[3]:=
Click for copyable input
Out[3]=
In[4]:=
Click for copyable input
Out[4]=

Position gives keys in an association:

In[5]:=
Click for copyable input
Out[5]=

Append to an association:

In[1]:=
Click for copyable input
Out[1]=

Delayed rules can be used to construct associations whose values are stored unevaluated:

In[1]:=
Click for copyable input
Out[1]=

The value in the association is evaluated when it is extracted:

In[2]:=
Click for copyable input
Out[2]=

Values in associations can be extracted like parts:

In[1]:=
Click for copyable input
Out[1]=

If the key in an association is a string, no explicit Key is needed to extract it as a part:

In[2]:=
Click for copyable input
Out[2]=

Numerical part specifications work structurally on associations:

In[3]:=
Click for copyable input
Out[3]=

Lookups in associations interoperate with parts in lists and other expressions:

In[4]:=
Click for copyable input
Out[4]=

The explicit Key can be omitted when the keys are strings:

In[5]:=
Click for copyable input
Out[5]=

Keys extracts the list of keys:

In[1]:=
Click for copyable input
Out[1]=

Associations can be modified by resetting values:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=
In[3]:=
Click for copyable input
Out[3]=
Introduced in 2014
(10.0)