title: Pandas MultiIndex (more than 2 levels) DataFrame to Nested Dict/JSON
body: <p>This question is similar to <a href="https://stackoverflow.com/questions/47920624/convert-pandas-multiindex-dataframe-to-nested-dictionary">this one</a>, but I want to take it a step further. Is it possible to extend the solution to work with more levels? Multilevel dataframes' <code>.to_dict()</code> method has some promising options, but most of them will return entries that are indexed by tuples (i.e. <code>(A, 0, 0): 274.0</code>) rather than nesting them in dictionaries.</p>
  
  <p>For an example of what I'm looking to accomplish, consider this multiindex dataframe:</p>
  
  <pre><code>data = {0: {
          ('A', 0, 0): 274.0, 
          ('A', 0, 1): 19.0, 
          ('A', 1, 0): 67.0, 
          ('A', 1, 1): 12.0, 
          ('B', 0, 0): 83.0, 
          ('B', 0, 1): 45.0
      },
      1: {
          ('A', 0, 0): 254.0, 
          ('A', 0, 1): 11.0, 
          ('A', 1, 0): 58.0, 
          ('A', 1, 1): 11.0, 
          ('B', 0, 0): 76.0, 
          ('B', 0, 1): 56.0
      }   
  }
  df = pd.DataFrame(data).T
  df.index = ['entry1', 'entry2']
  df
  # output:
  
           A                              B
           0              1               0
           0      1       0       1       0       1
  entry1   274.0  19.0    67.0    12.0    83.0    45.0
  entry2   254.0  11.0    58.0    11.0    76.0    56.0
  </code></pre>
  
  <p>You can imagine that we have many records here, not just two, and that the index names could be longer strings. How could you turn this into nested dictionaries (or directly to JSON) that look like this:</p>
  
  <pre><code>[
   {'entry1': {'A': {0: {0: 274.0, 1: 19.0}, 1: {0: 67.0, 1: 12.0}},
    'B': {0: {0: 83.0, 1: 45.0}}},
   'entry2': {'A': {0: {0: 254.0, 1: 11.0}, 1: {0: 58.0, 1: 11.0}},
    'B': {0: {0: 76.0, 1: 56.0}}}}
  ]
  </code></pre>
  
  <p>I'm thinking some amount of recursion could potentially be helpful, maybe something like <a href="https://stackoverflow.com/questions/19798112/convert-pandas-dataframe-to-a-nested-dict/19900276#19900276">this</a>, but have so far been unsuccessful.</p>