I have a ragged Association
of Association
, say :
assoc = Association[
"1" -> Association["a" -> "x", "b" -> "y"],
"2" -> Association[ "b" -> "z", "c" -> "k"]
]
I would like to transform it into a Association
where level 1 and level 2 keys are reversed, that is to say :
Association[
"a" -> Association["1" -> "x"],
"b" -> Association["1" -> "y", "2" -> "z"],
"c" -> Association[ "2" -> "k"]
]
My solution is :
keysExplodedList = Reap[MapIndexed[Sow[Reverse[#2] -> #1] &, assoc, {2}]][[2, 1]]
groupedLevel1 = GroupBy[#[[1, 1]] &] @ keysExplodedList
groupedLevel2 = GroupBy[#[[1, 2]] &] /@ groupedLevel1
result = Map[#[[1, 2]] &, groupedLevel2, {2}]
<|"a" -> <|"1" -> "x"|>, "b" -> <|"1" -> "y", "2" -> "z"|>, "c" -> <|"2" -> "k"|>|>
Is there something more elegant ?
(Reap[MapIndexed[Sow[#2 -> #1] &, assoc, {2}]][[2, 1]] // GroupBy[{#[[1, 2]] &, #[[1, 1]] &}])[[All, All, 1, 2]]
$\endgroup$