Python Forum

Full Version: convert List of Dicts into a 2 deep Nested Dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

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

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

MyListofDicts = [{'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'}
]
I need to convert this into a nested dictionary so that i can use it to build an html table with jinja2 templating ...The final HTML 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



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


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'
                  }
          }
   }
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


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 :(

Any help would be greatly appreciated
It should be pretty easy. Start with an empty main dictionary. Loop through the list. If the user name is not in the main dictionary, add it as a key with an empty sub-dictionary as the value. Then add the game to the sub-dictionary.

Try that. If it doesn't work, show us the code you wrote and what the problem is, and we can help you fix it.