convert List of Dicts into a 2 deep Nested Dict : <p>Ive been banging my head against a wall for some time with this now, so hoping somebody will be able to point me in the right direction</p>

<p>I am writing a flask app and my query returns the following list of dictionaries (via cur.fetchall) ..</p>

<pre><code>MyQueryResult = [{'gameID': 'game_1',
  'prediction': 41,
  'bonus': 'no',
  'userName': 'Paul'},
 {'gameID': 'game_2',
  'prediction': 77,
  'bonus': 'no',
  'userName': 'Paul'},
 {'gameID': 'game_1',
  'prediction': 62,
  'bonus': 'no',
  'userName': 'Steve'},
 {'gameID': 'game_2',
  'prediction': 77,
  'bonus': 'yes',
  'userName': 'Steve'}
]
</code></pre>

<p>I need to convert this into a nested dictionary so that i can use it to build an html table with jinja2 templating ...the table will have 'gameID' as Y axis, 'userName' as X axis,  with prediction as the value in the table.. there could be any number of games or users in any particular week</p>

<p>Ideally, for me to iterate over it in jinja2, i need to convert the above 'flat' list of dictionaries to a nested dictionary keyed on 'userName' and then 'gameID'  ..so that it looks like this</p>

<pre><code>MyDict = {
  'Paul': {
      'game_1': {
                'prediction': 'home_win', 'bonus': 'no'
                  },
      'game_2': {
                'prediction': 'away_win', 'bonus': 'no'
                  }},
   'Steve': {
       'game_1': {
                'prediction': 'home_win', 'bonus': 'no'
                  },
       'game_2': {
                'prediction': 'away_win', 'bonus': 'yes'
                  }
          }
   }
</code></pre>

<p>This format will enable me to iterate over on a per user /per game basis in Jinja2 and thus enable me to build a table</p>

<p>Does anyone have any idea on how i can perform the above conversion ...ive been trying for ages now and really struggling to figure it out :(</p>

<p>Any help would be greatly appreciated</p>
