0

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?

3
  • how about eval(user+'_hx'), although eval is not recommended Commented Jul 26, 2012 at 22:29
  • I don't see where you're accessing any files. Commented Jul 26, 2012 at 22:29
  • yeah Im missing something here... its not clear what you are trying to do... do you mean "%s_hx"%user[key] ? you open a file with open(filename,fileMode) Commented Jul 26, 2012 at 22:29

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I would definitely not recommend doing this ever. It's marginally better than eval but still worse than just using a dict of dicts which is what I'm guessing would be the right solution here.
There's no need to do this. Just put the dictionaries inside another dictionary. The globals() function just returns the global dictionary, anyway.
0
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?/

Comments

0

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.

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.