Hello,
I have a text file that goes like this:
bulbasaur,5,25.0,grass
charmander,3,100.0,fire
gyrados,1,1000.0,water,flying
squirtle,2,50.0,water
I’ve been trying to write a code that would load the texts as a nested dictionary like this:
’ ’ ’ python
pokemon = {
‘charmander’:{‘quantity’:3,‘fee’:100,‘powers’:[‘fire’]},
‘squirtle’:{‘quantity’:2,‘fee’:50,‘powers’:[‘water’]},
‘bulbasaur’:{‘quantity’:5,‘fee’:25,‘powers’:[‘grass’]},
‘gyrados’:{‘quantity’:1,‘fee’:1000,‘powers’:[‘water’,‘flying’]}
}
’ ’ ’
For now I have the following code:
’ ’ ‘python
pokemon = {}
database_filename = ‘pokemons.txt’
with open(database_filename) as file:
for line in file:
attributes = line.strip().split(’,’)
#print(attributes)
pokemon[attributes[0]] = [int(attributes[1]), float(attributes[2]), attributes[3:]]
def save():
with open(database_filename, ‘w’) as f:
for pok in sorted(pokemon):
f.write(pok + ‘,’ + str(pokemon[pok][0]) + ‘,’ + str(pokemon[pok][1]) + ‘,’ + ‘,’.join(pokemon[pok][2]) + ‘\n’)
’ ’ ’
I’ve written it so that (1) it reads the text file into a list and (2)saves it as a list but I am stuck on basically doing it the same for a nested dictionary