David Greydanus
David Greydanus

Reputation: 2567

How to permanently modify a dictionary in python?

I am making a program that records user behavior as they play a game, and improves its performance based off of that data {(User makes this move when this happens):(Do this)}. The problem is that I am storing all of that data in a dictionary in a separate module, so if I close the program everything will return to defaults.

Please tell me if there is a better way to store the data, or a way to permanently rewrite the program.

Thanks as always.

Upvotes: 2

Views: 1565

Answers (2)

VDes
VDes

Reputation: 66

Lately I've been persidict when it comes to persistent dictionaries. But shelve or pickle are also options for your task.

Upvotes: 1

MxLDevs
MxLDevs

Reputation: 19526

Storing it in a file is one option. Python comes with a Pickle module that allows you to pickle your dictionary. Then you store it locally on their disk, and then when you need to load it again use Pickle to load it when they start the game again.

EDIT:

As suggested by @alko, the shelve module would be a better option in your case since the data you're working with is already a dictionary.

For example, suppose you have some code that looks like

data = {}
data["coords"] = [1,2]

You can easily convert that to a shelf by simply changing one line and adding another (may be an over-simplification)

data = shelve.open("some_filename") # create a shelf instead
data["coords"] = [1,2]
data.close()                        # remember to close it

And now you have persistent storage without having to change any of your dictionary-access code.

Note that if the filename that you specify already exists, it will simply open it and allow you to read/write, so you don't need any additional logic to distinguish a player playing your game the first time, and a player continuing from a previous session.

Upvotes: 4

Related Questions