Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Look up a set of keys in order to get deeper parts of an association or list of rules
ResourceFunction["NestedLookup"][assoc,{key1,key2,…}] looks up the value associated with the keys key1,key2,… in deeper levels of assoc. | |
ResourceFunction["NestedLookup"][assoc,keys, default] gives default if the part specified by keys is not found. | |
ResourceFunction["NestedLookup"][{key1,key2,…}] represents an operator form of ResourceFunction["NestedLookup"] that can be applied to an expression. |
Retrieve the ResourceFunction:
| In[1]:= |
| Out[1]= |
Look up a nested part of an association:
| In[2]:= |
| Out[2]= |
When a key is not found, a Missing object is returned:
| In[3]:= |
| Out[3]= |
When a third argument is provided and the key sequence has a part missing, the default value is returned:
| In[4]:= |
| Out[4]= |
When the key sequence is present, the default is not evaluated:
| In[5]:= |
| Out[5]= |
NestedLookup threads over lists of associations:
| In[6]:= | ![]() |
| In[7]:= |
| Out[7]= |
NestedLookup can be used to look up keys in lists of rules:
| In[8]:= |
| Out[8]= |
Lists of rules can be mixed with Associations:
| In[9]:= |
| Out[9]= |
Use the operator form of NestedLookup:
| In[10]:= |
| Out[10]= |
You can use constructs such as Throw and Return in the third argument of NestedLookup to abort a computation when a required key is missing:
| In[11]:= | ![]() |
| In[12]:= |
| Out[12]= |
| In[13]:= |
| Out[13]= |
Applying an Association to a sequence of keys is typically equivalent to using NestedLookup on a list of those keys:
| In[14]:= |
| Out[14]= |
| In[15]:= |
| Out[15]= |
Lists are handled differently by NestedLookup, however:
| In[16]:= |
| Out[16]= |
| In[17]:= |
| Out[17]= |
Wrap the list in Key to make NestedLookup treat it as a single key:
| In[18]:= |
| Out[18]= |
When the key to be looked up is a list or an expression with head Key, it must be wrapped in Key to avoid ambiguity:
| In[19]:= |
| Out[19]= |
| In[20]:= |
| Out[20]= |
| In[21]:= |
| Out[21]= |
| In[22]:= |
| Out[22]= |
| In[23]:= |
| Out[23]= |
When a part is not found, NestedLookup only reports the sequence up to the missing key:
| In[24]:= |
| Out[24]= |
Wolfram Language 11.3 (March 2018) or above
This work is licensed under a Creative Commons Attribution 4.0 International License