Skip to content
Advertisement

Creating a nested dictionary from a pandas dataframe

I have a dataframe which demonstrates a hierarchy of meters. A meter has an ID, and can have any number of children, this children can also have children, which can also have children, ad infinitum.

The dataframe has a meter per row, and the level of the child is shown by column. As shown below:

hierarchy table

The aim is to convert it to a nested dictionary in the following format:

JavaScript

I have managed to achieve this, using the scary code you can see below (sorry). I was wondering if there is a tool that can do this for you, or if there is a cleaner, more readable way of accomplishing this.

Note this only goes up to a nesting level of 4, but can be easily extended further.

JavaScript

Advertisement

Answer

You can use itertools.groupby with recursion:

JavaScript

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement