2 flat arrays (keys/values) to nested JSON
12:03 26 Jun 2026

In short I need to go from

keys = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
values = ['12', '9', '4', '5', '14', '6', '3', '3', '10', '9', '4', '6', '11', '4']

to

{
    "name": "graph",
    "children": [
        {"name": "1", "value": 25, "children": [
            {"name": "a", "value": 12},
            {"name": "b", "value": 9},
            {"name": "c", "value": 4}
        ]},
        {"name": "2", "value":25, "children": [
            {"name": "a", "value": 5},
            {"name": "b", "value": 14},
            {"name": "c", "value": 6}
        ]},
        {"name": "3", "value":25, "children": [
            {"name": "a", "value": 3},
            {"name": "b", "value": 3},
            {"name": "c", "value": 10},
            {"name": "d", "value": 9}
        ]},
        {"name": "4", "value":25, "children": [
            {"name": "a", "value": 4},
            {"name": "b", "value": 6},
            {"name": "c", "value": 11},
            {"name": "d", "value": 4}
        ]}
    ]
}

In case you're curious, the JSON will be used to produce a sunburst chart using primaviz, a Typst package:

#import "@preview/primaviz:0.8.0": *
#sunburst-chart(json("file.json"))

What steps do you think I should take to go about this?

I tried to order the lists first:

ordered_questions = [ list('a' + s) for s in ''.join(questions).split('a')[1:]]
ordered_marks = [arr.tolist() for arr in np.split(marks, np.cumsum([len(row) for row in ordered_questions])[:-1])]

but that seemed to have made the following steps more difficult!

python arrays json dictionary data-conversion