title: Pandas: Convert DataFrame with MultiIndex to dict
body: <p>Another novice pandas question. I want to convert a DataFrame to a dictionary, but in a way different from what is offered by the <code>DataFrame.to_dict()</code> function. Explanation by example:</p>
  
  <pre><code>df = pd.DataFrame({'co':['DE','DE','FR','FR'],
                     'tp':['Lake','Forest','Lake','Forest'],
                     'area':[10,20,30,40],
                     'count':[7,5,2,3]})
  df = df.set_index(['co','tp'])
  </code></pre>
  
  <p>Before:</p>
  
  <pre><code>           area  count
  co tp
  DE Lake      10      7
     Forest    20      5
  FR Lake      30      2
     Forest    40      3
  </code></pre>
  
  <p>After:</p>
  
  <pre><code>{('DE', 'Lake', 'area'): 10,
   ('DE', 'Lake', 'count'): 7,
   ('DE', 'Forest', 'area'): 20,
   ...
   ('FR', 'Forest', 'count'): 3 }
  </code></pre>
  
  <p>The dict keys should be tuples consisting of the index row + column title, while the dict values should be the individual DataFrame values. For the example above, I managed to find this expression:</p>
  
  <pre><code>after = {(r[0],r[1],c):df.ix[r,c] for c in df.columns for r in df.index}
  </code></pre>
  
  <p>How can I <em>generalize this code to work for MultiIndices with N levels</em> (instead of 2)?</p>
  
  <p><strong>Answer</strong></p>
  
  <p>Thanks to <a href="https://stackoverflow.com/a/17682489/2375855">DSM's answer</a>, I found that I actually just need to use tuple concatenation <code>r+(c,)</code> and my 2-dimensional loop above becomes N-dimensional:</p>
  
  <pre><code>after = {r + (c,): df.ix[r,c] for c in df.columns for r in df.index}
  </code></pre>