Reputation: 1
I'm a newb trying to figure out how to accomplish the following:
I have dicts named after users in the following format:
<user>_hx
I want to access them with a function like so:
def foo(user, other_stuff):
user_hx[key]
......etc.
I attempted to access with % as follows:
def foo(user, other_stuff):
%r_hx %user[key]
but for obvious reasons I know that can't work.
Adivce?
Upvotes: 0
Views: 58
Reputation: 43024
Don't use the name as a variable. You can put your collection of dictionaries inside another, top-level, dictionary with those names as keys.
users = {
"user1_hx": {"name": "User 1"},
"user2_hx": {"name": "User 2"),
}
etc.
Then access as:
realname = users["%s_hx" % name]["name"]
etc.
Upvotes: 0
Reputation: 113978
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?/
Upvotes: 0
Reputation: 3616
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
Upvotes: 1