Skip to content
Advertisement

Pandas dataframe from nested dictionary

My dictionary looks like this:

JavaScript

I want to get a dataframe that looks like this:

JavaScript

I tried calling pandas.from_dict(), but it did not give me the desired result. So, what is the most elegant, practical way to achieve this?

EDIT: In reality, my dictionary is of depth 4, so I’d like to see a solution for that case, or ideally, one that would work for arbitrary depth in a general setup.

Here is an example of a deeper dictionary: {'x':{'a':{'m':1, 'n':2}, 'b':{'m':10, 'n':20}}, 'y':{'a':{'m':100, 'n':200}, 'b':{'m':111, 'n':222}} } The appropriate dataframe should have 8 rows.

ANSWER:

JavaScript

Advertisement

Answer

You can use a list comprehension to reorder your dict into a list of tuples where each tuple is a row and then you can sort your dataframe

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