Dictionary creator (Python 3.x)

Question:

Rather than typing manually all the monsters I want to use in my text game, I want to build a program to automatically add to the dictionary via IDLE. My question is how to collect and save the new monsters I add in IDLE. Is there a way to make a program that would write the information into a notepad? I looked for similiar answers and didn’t see anything. But I don’t necessarily know the right terminology. Thanks!

"""
Dictionary of indexed "monsters" for text game
"""
### Premade dictionary
mondic =  {1:'dragon',
           2:'angry gnome vigilante',
           3:'Donald Trump',
           4:'lambhorn rider',
           5:'bone cancer'}
print(mondic)
check = 'yes'
x = 5
### Create new monsters
while check == 'yes':
    print('Do you want to create a monster?')
    check = str(input('yes/no '))
    if check == 'no':
        break
    new_monster = str(input('New monster name: '))
    x += 1
    mondic[new_monster] = x
print(mondic)
Asked By: Zphinx677

||

Answers:

First of all, you don’t need to use a dictionary for this. Because you are just storing the names at indices, a list is much better suited for this problem. You will want code like this:

monlist = ['dragon', 'angry gnome vigilante', 'Donald Trump', 'lambhorn rider', 'bone cancer']
while check == 'y':
    check = input('Do you want to create a monster? (y/n): ')
    if check == 'n':
        break
    new_monster = input('New monster name: ')
    monlist.append(new_monster)

Then to write these to a file:

fv = open("filename.txt", 'w') # 'w' for write
for monster in monlist:
    print(monster, file=fv)
fv.close() # close the file

And to read:

monlist = []
open("filename.txt", 'w')
for line in fv:
    monlist.append(line)
fv.close()

See the documentation for more information. Keep in mind that there are other ways to read and write data, and as you get further into your project you may discover that you need to write your own classes or actually use a dictionary. Then you may need to serialize data, use json encoding, or find some other way to save/read data. Good luck!

Answered By: Jacob H
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.