我是一个新手,试图弄清楚如何完成以下任务:
我有以下格式的以用户命名的字典:
<user>_hx
我想使用如下函数访问它们:
def foo(user, other_stuff):
user_hx[key]
......ETC。
我尝试使用 % 访问如下:
def foo(user, other_stuff):
%r_hx %user[key]
但由于显而易见的原因,我知道这是行不通的。
建议?
我是一个新手,试图弄清楚如何完成以下任务:
我有以下格式的以用户命名的字典:
<user>_hx
我想使用如下函数访问它们:
def foo(user, other_stuff):
user_hx[key]
......ETC。
我尝试使用 % 访问如下:
def foo(user, other_stuff):
%r_hx %user[key]
但由于显而易见的原因,我知道这是行不通的。
建议?
What I think you are asking is how to access a variable based on a string representing its name. Python makes this quite easy:
globals()['%s_hx' % user]
will give you the variable <user>_hx
, so you just want
globals()['%s_hx' % user][key]
(I'm not sure whether you should be using globals()
or locals()
; it will depend on how your variables are defined and where you are trying to access them from)
That said, there is probably an easier/cleaner way to do whatever you are doing. For instance, have you considered putting all these dictionaries in a 'master' dictionary so that you can pass them around, as well as just access them
不要将名称用作变量。您可以将您的字典集合放在另一个顶级字典中,并将这些名称作为键。
users = {
"user1_hx": {"name": "User 1"},
"user2_hx": {"name": "User 2"),
}
等等
然后访问为:
realname = users["%s_hx" % name]["name"]
等等
def foo(user,other_stuff):
fname = "%s_hx"%user[key] #not sure where key is comming from... but would result in something like "bob_hx"
with open(fname) as f:
print f.read()
maybe?/