elfxx elfxx - 8 months ago 18
Python Question

How to change keys to values in hierarchical python dictionary

I have a hierarchical python dict as below:

{'4a': {'3a': {'2a1': {'1a1.2': 'size', '1a1.1': 'size'}, '2a2': {'1a1': 'size'}}}}

I want to convert this to json data, like:

{"name":'1a1.2, "size":'size'},
{"name":'1a1.1', "size":'size'}
{"name":'1a1', "size":'size'}

How can I add "name" and "children" quantities and list elements to the dictionary. Any suggestions would be very helpful!


You can use a recursive function like this:

def convert(d):
    res = []
    for k, v in d.items():
        if isinstance(v, dict):
            res.append({'name': k, 'children': convert(v)})
        elif isinstance(v, int):
            res.append({'name': k, 'size': v})
    return res

Here, I am assuming that 'size' should actually be a numeric value in the original dictionary.


>>> dictionary = {'4a': {'3a': {'2a1': {'1a1.2': 123, '1a1.1': 456}, '2a2': {'1a1': 789}}}}
>>> pprint.pprint(convert(dictionary))
[{'children': [{'children': [{'children': [{'name': '1a1', 'size': 789}],
                              'name': '2a2'},
                             {'children': [{'name': '1a1.2',
                                            'size': 123},
                                           {'name': '1a1.1',
                                            'size': 456}],
                              'name': '2a1'}],
                'name': '3a'}],
  'name': '4a'}]