3
$\begingroup$

How do you iterate over the keys or rules of an association (in any order)? E.g. for

<|"0"->"a", "1"->"b", "2"->"c"|>

I would like to either iterate over "0", "1", "2" or tuples containing each key and value.

For example, something that performed the equivalent of a python dictionary's items, method would be ideal (which returns a list (or iterator) in the form [(key1, value1), ...], so {{"0", "a"}, {"1", "b"}, {"2", "c"}} here).

$\endgroup$
  • 1
    $\begingroup$ Simply use Map, KeyValueMap or KeyMap? $\endgroup$ – Henrik Schumacher Dec 5 '18 at 19:20
  • $\begingroup$ Can you tell what exactly do you want to do? $\endgroup$ – Kuba Dec 5 '18 at 21:42
  • $\begingroup$ Woooops! Done! :) $\endgroup$ – SLesslyTall Dec 6 '18 at 7:40
  • $\begingroup$ @SLesslyTall You see, you want KeyValueMap[List] @ asso but who could've known :) $\endgroup$ – Kuba Dec 6 '18 at 7:53
2
$\begingroup$

To iterate over the keys of an association, first get the keys in a list using Keys. then use this in your favorite iteration construct (Do, Table, Scan, Map, etc):

In[16]:= assoc = <|"0" -> 0, "1" -> 1, "2" -> 2|>;

In[17]:= Do[Print[x], {x, Keys[assoc]}]

During evaluation of In[17]:= 0

During evaluation of In[17]:= 1

During evaluation of In[17]:= 2
$\endgroup$
6
$\begingroup$

If you would like to map over the keys to transform them into something else, you can use KeyMap:

a = <|"0" -> 0, "1" -> 1, "2" -> 2|>;
a // KeyMap[("newKey" <> #) &]
(* <|"newKey0" -> 0, "newKey1" -> 1, "newKey2" -> 2|> *)

Otherwise, the good old Map will iterate over the values as if the structure were a list:

a // Map[("newVal" <> ToString@#) &]
(* <|"0" -> "newVal0", "1" -> "newVal1", "2" -> "newVal2"|> *)

You should also look up KeyValueMap to see if that would make your task easier.

Edit

Henrik Schumacher's succinct comment contains everything I have elaborated here. His comment had not been posted when I began writing this answer.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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