oTree Forum >

How to keep changes on dictionary in before_next_page function preserved

#1 by HJmonica

Hi helpers,

I have a question regarding sequentially generating a dictionary to save the win-or-lose statues of single-player game. Specifically, I typed "class Player(BasePlayer):record = models.LongStringField(initial='{}')" in models.py.

For pages.py, I typed "class Win(Page): 
def before_next_page(self): record_dict = json.loads(self.player.record)
record_dict[last_round-1] = 1
self.player.record = json.dumps(record_dict)" to add a new term in the dictionary, while 1 means "win".

Similarly, I typed "class Lose(Page): 
def before_next_page(self): record_dict = json.loads(self.player.record)
record_dict[last_round-1] = 0
self.player.record = json.dumps(record_dict)" to add a new term in the dictionary, while 0 means "lose".

I aim to repeat the game for multiple rounds. However, after checking the output, when the page arrives win or lose in the later rounds, the dictionary is empty, meaning that no records was kept. 

My question is, to really store the records in the dictionary I created, what should I do?

Many thanks!!

Best,
Monica

#2 by woodsd42

Try participant fields : https://otree.readthedocs.io/en/latest/rounds.html#participant-fields

What you suggest wouldn't work as fields are round based and 'fresh' each round, so you'd have to use in_previous_rounds() or similar, but really participant fields is the correct way to do this.

#3 by HJmonica

Thanks for the reply!

Could you be more specific about how to add a list in participant field and make it work?

I tried typing PARTICIPANT_FIELDS = ['record'] in settings.py, and typing 
def before_next_page(self):
        record_dict = json.loads(self.participant.record)
        
in pages.py, but there is an error message "KeyError: 'record'" indicating that the key is not found.

#4 by woodsd42

You need to initialize the dictionary, either in creating_session() ( but make sure you do it only in the first round ) or using something like get, which can specify a default if nothing is there, but I've forgotten the syntax. 

I wonder, given your programming skills, whether you need to use such advanced features to successfully implement the experiment you have in mind .  Personally, I don't use json outside of live pages, and if the number of fields is fixed, then you could just use the player and in_previous_rounds() to get at that.

Write a reply

Set forum username