5
$\begingroup$

Is it possible to iterate over the values of the deepest layer of keys in a nested association? For example:

assoc = <| "a"->0, "b"-> <| "c"->"one" ,"d"->2 , "e"->3|>, "f"->4|>

Would it be possible to iterate over just the values of at the deepest level in this example {0,"one",2,3,4}? Or, possible to iterate over the deepest level of keys such that I could test the type for the value of each key?

$\endgroup$

3 Answers 3

8
$\begingroup$
Level[assoc, {-1}]
(*    {0, "one", 2, 3, 4}    *)
$\endgroup$
1
  • $\begingroup$ That is pretty nifty. Thanks! $\endgroup$
    – kickert
    Jun 27, 2019 at 21:02
5
$\begingroup$
assoc /. Association -> (Values@*List) // Flatten

{0, "one", 2, 3, 4}

When some values are non-atomic this approach and the deepest Level approach give different results:

assoc2 = <| "a" -> foo[0],  "b" -> <| "c" -> "one" , "d" -> 2 , "e" -> 3|>, 
   "f" -> {bar[1], foo[3]}|>;

assoc2 /. Association -> (Values@*List) // Flatten

{foo[0], "one", 2, 3, bar[1], foo[3]}

Level[assoc2, {-1}]

{0, "one", 2, 3, 1, 3}

$\endgroup$
4
$\begingroup$
Map[
 AssociationMap[
  keyTest[#[[1]]] -> valueTest[#[[2]]] & 
  ],
 <|"a" -> 0, "b" -> <|"c" -> "one", "d" -> 2, "e" -> 3|>, "f" -> 4|>,
 {-2}
 ]

<|"a" -> 0, 
 "b" -> <|keyTest["c"] -> valueTest["one"], keyTest["d"] -> valueTest[2], 
   keyTest["e"] -> valueTest[3]|>, "f" -> 4|>
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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