-1

I am working to convert 3 levels of the nested dictionary to the data frame.

I found a code online and it actually worked. Being a newbie, I am just looking for an explanation of the code, if possible on this platform.

Could you please explain to me the bolded line, how is it going inside the dictionary and converting the data?

The code that works is:

csv = pd.DataFrame.from_dict({**(i,j): data_df[i][j]** 
                           for i in data_df.keys() 
                           for j in data_df[i].keys()},
                       orient='index')
David
  • 8,113
  • 2
  • 17
  • 36
Aman
  • 7
  • 2

1 Answers1

0

So I'm guessing the data_df is a dictionary of dictionaries.

So the following:

{(i,j): data_df[i][j] for i in data_df.keys() for j in data_df[i].keys()}

Is just a dictionary-comprehension. it takes the parent key i and one of the child key j and use a tuple, (i,j), of them as the new key of the dictionary and uses the child, j value as the new value.

That is basically what it does.

In order to emphasize it let's look at the following example:

d = {"apple": {"a":1,"b":2}, "orange": {"a":3, "b":4}}
new_d = {(i,j): d[i][j] for i in d.keys() for j in d[i].keys()}
print(new_d)  # {('apple', 'a'): 1, ('apple', 'b'): 2, ('orange', 'a'): 3, ('orange', 'b'): 4}

Another link to read about dictionary-comprhension

David
  • 8,113
  • 2
  • 17
  • 36