[英]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?我想知道是否有一种方法可以 map 在 for 循环或其他东西中将变量指向字典中的相应键,这样我就不必定义每一个? Thanks!谢谢!
Depending on the scope you can use globals
or locals
for this:根据 scope 您可以为此使用globals
或locals
变量:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.