How to index a subdictionary and creating a nested for loop

Viewed 102

I have a list of lists just like below:

>> new_pd[:3]
[['PokedexNumber',
  'Name',
  'Type',
  'Total',
  'HP',
  'Attack',
  'Defense',
  'SpecialAttack',
  'SpecialDefense',
  'Speed'],
 [1.0, 'Bulbasaur', 'GrassPoison', 318.0, 45.0, 49.0, 49.0, 65.0, 65.0, 45.0],
 [2.0, 'Ivysaur', 'GrassPoison', 405.0, 60.0, 62.0, 63.0, 80.0, 80.0, 60.0]]

What I want to create is below:

{1.0: {'Attack': 49.0,
  'Defense': 49.0,
  'HP': 45.0,
  'Name': 'Bulbasaur',
  'PokedexNumber': 1.0,
  'SpecialAttack': 65.0,
  'SpecialDefense': 65.0,
  'Speed': 45.0,
  'Total': 318.0,
  'Type': 'GrassPoison'},
 2.0: {'Attack': 62.0,
  'Defense': 63.0,
  'HP': 60.0,
  'Name': 'Ivysaur',

So from list of lists, I want to have a big nested dictionary.

To create this, I have written the below code in Python:

new_pd_keys = []
for i in range(1, len(new_pd)):
    new_pd_keys.append(new_pd[i][0]) 

Above, I get all the keys from column 1 and save them to a list called new_pd_keys.

Then use the below code to assign each keys' values:

for i in range(1,len(new_pd)):
    new_pd_dict = {key:{'Attack':new_pd[i][5], 'Defense':new_pd[i][6], 'HP':new_pd[i][4], 
          'Name':new_pd[i][1], 'PokedexNumber':new_pd[i][0], 'SpecialAttack':new_pd[i][7],
          'SpecialDefense':new_pd[i][8], 'Speed':new_pd[i][9], 'Total':new_pd[i][3], 
          'Type':new_pd[i][2]} for key in new_pd_keys }

But what I have is the attributes from my last row. You can see the output below, which are all the same.

{1.0: {'Attack': 110.0,
  'Defense': 120.0,
  'HP': 80.0,
  'Name': 'Volcanion',
  'PokedexNumber': 721.0,
  'SpecialAttack': 130.0,
  'SpecialDefense': 90.0,
  'Speed': 70.0,
  'Total': 600.0,
  'Type': 'FireWater'},
 2.0: {'Attack': 110.0,
  'Defense': 120.0,
  'HP': 80.0,
  'Name': 'Volcanion',
  'PokedexNumber': 721.0,
  'SpecialAttack': 130.0,
  'SpecialDefense': 90.0,
  'Speed': 70.0,
  'Total': 600.0,
  'Type': 'FireWater'},

Can you suggest a way to perform the indexing in a better way than mine?

1 Answers
new_thing = {q[0]: dict(zip(thing[0], q[1:])) for q in thing[1:]}
Related