Skip to main content

associations - Create Nested List from tabular data


Im trying to create a nested list from tabular data, then onward into a nested association. I can get part way with the help of this answer but it only works for the first level. Repeated use of this approach doesn't seem to work.


list=  {{"Category", "Detail", "Value"}, {"Cat1", "detail1", 23},

{"Cat1", "detail2", 27}, {"Cat1", "detail3", 13}, {"Cat2", "detail4",15},
{"Cat2", "detail5", 35}, {"Cat3", "Detail6", 56}};

list // TableForm

(* tabular data result *)

First level of data.


Thread[list[[2 ;;, 2]] -> #] & /@ {list[[2 ;;, 3]]} // ToAssociations


{<|detail1->23,detail2->27,detail3->13,detail4->15,detail5->35,Detail6->56|>}

Required result


{<| Cat1-> <|detail1->23,detail2->27,detail3->13|>|>,
<| Cat2-> <|detail4->15,detail5->35|>|>,
<| Cat3-> <|Detail6->56|>|>}

Update is it possible to come up with something that works for N levels of nesting?


Eg 3 levels of nesting


list = {{"BigCat", "Category", "Detail", "Value"}, {"BigCat", "Cat1", 

"detail1", 23}, {"BigCat", "Cat1", "detail2", 27}, {"BigCat",
"Cat1", "detail3", 13}, {"BigCat", "Cat2", "detail4",
15}, {"BigCat", "Cat2", "detail5", 35}, {"LittleCat", "Cat3",
"Detail6", 56}}

Answer



From my answer to Handy / flexible directory tree operations with minor modification:


fn[x_List] := GroupBy[x, First -> Rest, fn]

fn[{{x_}}] := x


Tested on your two lists, named list1 and list2 respectively:


fn[Rest @ list1]


<|"Cat1" -> <|"detail1" -> 23, "detail2" -> 27, "detail3" -> 13|>, 
"Cat2" -> <|"detail4" -> 15, "detail5" -> 35|>, "Cat3" -> <|"Detail6" -> 56|>|>

fn[Rest @ list2]



<|"BigCat" -> <|"Cat1" -> <|"detail1" -> 23, "detail2" -> 27, "detail3" -> 13|>, 
"Cat2" -> <|"detail4" -> 15, "detail5" -> 35|>|>,
"LittleCat" -> <|"Cat3" -> <|"Detail6" -> 56|>|>|>

Comments