I am trying to create a function that allows the user to view my full dictionary. I want to be able to output each nested dictionary together in a neat formation Like this:, instead of printing it out line by line
and
.
The dictioanry looks something like this:
#Dictionary for all the monster cards with a set of stats
monster_cards = {"Corpsemask":
{"Strength": 7,
"Speed": 1,
"Stealth": 25,
"Cunning": 15},
"Dustfigure":
{"Strength": 1,
"Speed": 6,
"Stealth": 21,
"Cunning": 19},
"Bonemonster":
{"Strength": 5,
"Speed": 15,
"Stealth": 18,
"Cunning": 22},
"Bonefoot":
{"Strength": 15,
"Speed": 20,
"Stealth": 23,
"Cunning": 6}}
I am a beginner with programming, and am doing a practice assessment, so I have a certain character count per line which is why the code may look weird. I also have to use the easygui module.
Any advice for this issue?
def view_catalogue():
if len(monster_cards) > 0:
for card, card_stats in monster_cards.items():
msg = easygui.msgbox("Monster: " + card)
for key in card_stats:
msg = easygui.msgbox(key + ": " + str(card_stats[key]))
else:
msg = easygui.msgbox("You have no monsters in your catalogue")
Here is my current function:
>Solution :
This is the problem:
for key in card_stats:
msg = easygui.msgbox(key + ": " + str(card_stats[key]))
Each time through this loop, you’re making a brand-new message box with just one stat line.
As @RandomDavis commented above, you probably want to do it like this:
msg = ""
for key in card_stats:
stat_line = key + ": " + str(card_stats[key]) + "\n"
msg += stat_line
easygui.msgbox(msg)