0

For my project I need to access variables in another file and update them.

In my Database.py file I have the following code:

stock = {"Bread" : 27,
"Car" : 1,
"Banana" : 3000}

In my main program I have this code:

from Database import *

print(stock)
stock['Banana'] -= 100
print(stock)

Running this code returns the expected

{'Car': 1, 'Banana': 3000, 'Bread': 27}
{'Car': 1, 'Banana': 2900, 'Bread': 27}

But since bananas don't magically restore between purchases, I need this variable to change persistently across several runs.

Carl Groth
  • 97
  • 1
  • 7
  • 1
    You need to dump your dictionary to a file to retrieve its latest state after you have manipulated the data. You can use the `json` module to achieve this. – idjaw Apr 17 '16 at 14:29
  • 1
    @idjaw: In this case `shelve` would be a good idea too. – Martijn Pieters Apr 17 '16 at 14:29
  • @MartijnPieters Absolutely. `pickle` also comes to mind. Actually, [this](http://stackoverflow.com/questions/4103430/what-is-the-difference-between-pickle-and-shelve) is a good comparison – idjaw Apr 17 '16 at 14:31
  • 1
    @idjaw: `shelve` uses `pickle` to handle storing the dictionary values. `shelve` is a great way to implement exactly what the OP wants: transparent persistence between runs. – Martijn Pieters Apr 17 '16 at 14:33
  • @MartijnPieters Yeah, a bit of a funny statement from me. Even states it in the post I linked `shelve builds on top of pickle`. :) – idjaw Apr 17 '16 at 14:37
  • Hey thanks for the help. I'm trying to call the function `shelve.open` but it doesn't recognize the filename. `d = shelve.open(database.py)` I've tried using `database.py` and `database` both returned `NameError: name 'database' is not defined` – Carl Groth Apr 17 '16 at 14:53

0 Answers0