pythondictionarynestedshelve

How do I get stored dictionaries' values from a shelve-file back into the program


I started learning Python 2 weeks ago, and now I am trying to code a text adventure game. However, I've run into a problem. So far, I haven't found any solution on Google which can help me.

I decided to store basically all relevant variables in dictionaries - feel free to tell me wether that's even a clever idea or rather stupid of me, I actually do not know this, I just thought it might be a solution that works.

Here's my problem: last thing I decided to insert into the program is a save_game() function. So I defined:

def save_game(data):
    import shelve
    savegame = shelve.open('./save/savegame')
    savegame['data'] = data
    savegame.close()

And of course, if I then call

save_game(save_game_data)

with save_game_data being the dictionary where I've put all the other dictionaries so I can handle saving with a single function call (I thought that might be better?), it actually works.

But of course a save_game() only makes sense if you can also reload the data into the program. So I defined:

def load_game(data):
    import shelve, time
    savegame = shelve.open('./save/savegame')
    data = savegame['data']
    data = dict(data) # This was inserted because I hoped it would solve my problem, but it doesn't
    savegame.close()

But the result of

load_game(save_game_data)

Unfortunately is no updated dictionary save_game_data with all the keys and values, and I just can't get my head around how to get all the stored data back into values in the dictionaries. Maybe I'm on a totally wrong way all together, maybe I just don't know enough about Python yet to even know where I'm erring.

The save_game() and load_game() functions are in a different file from the main file, and are correctly imported if that is relevant.


Solution

  • It looks like you're trying to pass save_game_data to load_game() as if to mean "load data and put it into save_game_data" but this isn't what load_game() is doing. By doing this:

    def load_game(data):
        import shelve, time
        savegame = shelve.open('./save/savegame')
        data = (savegame['data'])
    

    You're replacing what data refers to, so save_game_data doesn't get changed.

    Instead, you can drop the argument to load_game() and add:

    return data
    

    at the end of the function, and call it like this:

    save_game_data = load_game()