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$
7
$\begingroup$
Level[assoc, {-1}]
(*    {0, "one", 2, 3, 4}    *)
$\endgroup$
  • $\begingroup$ That is pretty nifty. Thanks! $\endgroup$ – kickert Jun 27 at 21:02
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$
4
$\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$

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.