0

I'm making a game that saves information such as funds and stuff like that about users in a shelve. That shelve starts out looking something like this:

Userdata = shelve.open('UserData', writeback = True)
Userdata[username]={'funds' = 100, 
                    'highscore' = 0}

The username variable is defined earlier. The shelve has keys that are usernames, and the values are dictionaries with that user's data. And then, I have some in-game variables that correspond to the values stored in the dictionary:

funds = Userdata[username]['funds']
highscore = Userdata[username]['highscore']

The variables in the dictionary get changed as the user changes the in-game values. The names of the variables will always be the same as the corresponding dictionary key. The problem is, I have quite a few variables in the dictionary. I was wondering if there was a way to map the variables to the corresponding keys in the dictionary in a for loop or something, so that I don't have to define every single one? Thanks!

4
  • Why do you need them in a variable name if you're not willing to type it out? By adding them with a for loop you'd likely create a bunch of variables you aren't actually going to use Is there a reason that using them in data stores that are keyed on strings don't work for you? Commented Jan 6, 2021 at 0:50
  • 1
    IMHO your variables are too small. They should be members of a class and then you have userstate = Userdata[username] only. You'd then access the funds using userstate.funds and the highscore by userstate.highscore. Commented Jan 6, 2021 at 0:51
  • I agree with @ThomasWeller,if your data loaded from shelve is a json string, you could use json module to parse to a dict, then you can use userstate.funds to arrive the member variable Commented Jan 6, 2021 at 1:01
  • @ThomasWeller thank you! I just started writing the whole thing again as a class, and this is very helpful. Commented Feb 17, 2021 at 0:07

1 Answer 1

1

Depending on the scope you can use globals or locals for this:

In [1]: d = {'funds': 100, 'highscore': 0}
   ...: for k in d:
   ...:     locals()[k] = d[k]

In [2]: funds
Out[2]: 100

In [3]: highscore
Out[3]: 0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.