Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

how to map dictionary keys to variables in python?

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...