Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
For an inventory system I'm making for my game I need to use dictionaries and be able to show their contents in a screen, the dictionary seems to be working fine but when I try to show it's contents, Ren'Py throws me an error. Here's what I have been testing with:
default a_dict = {'a':1,'b':2,'c':3}
screen test_dict(d):
frame:
vbox:
for k in d.keys():
text "[k] has value [d[k]]." # <-- I think the problem is here
label start:
show screen test_dict(a_dict)
When I run the game, this error shows up (Only putting the relevant part here):
I'm sorry, but an uncaught exception occurred.
File "game/script.rpy", line 16, in execute
text "[k] has value [d[k]]."
KeyError: u'k'
I imagine it's a conflict with the brackets inside the brackets needed to access the key's value. Is there another way I can show this value without using the []?
Last edited by RicharDann on Wed Oct 04, 2017 10:14 am, edited 1 time in total.
You can't "double" interpolate with brackets -- in other words, [d[k]] is looking for the value of a_dict[k], which doesn't exist. Either use .format interpolation (which you can search for) or string concatenation (i.e., "[k] has value " + str(d[k])).
philat wrote: ↑Wed Oct 04, 2017 9:37 am
use .format interpolation (which you can search for) or string concatenation (i.e., "[k] has value " + str(d[k])).
Oh of course *facepalm* why didn't I think of that? str() works just fine, thanks!
Last edited by RicharDann on Wed Oct 04, 2017 11:48 am, edited 1 time in total.
You could also interpret the value within the for loop:
for key, value in d.iteritems():
.... text "[key] = [value]"
You will find though, with dictionary keys being unordered that it might be best to iterate a sorted list rather than leave it to chance as to which order they are output...
for key, value in sorted( d.items() ):
.... text "[key] = [value]"
Remix wrote: ↑Wed Oct 04, 2017 10:38 am
You could also interpret the value within the for loop:
for key, value in d.iteritems():
.... text "[key] = [value]"
You will find though, with dictionary keys being unordered that it might be best to iterate a sorted list rather than leave it to chance as to which order they are output...
for key, value in sorted( d.items() ):
.... text "[key] = [value]"
Hey, that's an interesting approach too, and you're right I might need to sort the items in the future so I will be sure to keep your advice in mind, thank you both for your help!