0

I'm coding a text-based adventure game for my python project in school, and I'm currently creating a fight function. It involves a lot of dictionaries, hence why I need to refer to a variable from a string. Here is an example of what I am asking!

some_dict = {
 'one':1,
 'two':2
 }
x = 'some_dict'
print(x)
print(x['one'])

I want it to print the dictionary dict, not the string 'dict'. Then on the second print, I would want it to print the value in 'one', from the dictionary dict. Is there some function that can convert the string to a variable some how or check for a variable matching the string? Or something along those lines? Thank you so much!

paochy
  • 11
  • 5
  • 2
    1. Don't use `dict` to name a variable. 2. Dynamic variable is almost never a good idea: see https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables. – j1-lee Oct 11 '21 at 04:46
  • _It involves a lot of dictionaries_ - who about putting those dictionaries in an outer `dict` using is name as key. – tdelaney Oct 11 '21 at 04:47

2 Answers2

1

Use globals if it's a global variable (outside aa function):

print(globals()[x]['one'])

If it's in a function:

print(locals()[x]['one'])
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 2
    I wish I could upvote this instead of commenting bc I know you're not supposed to comment thanks but I don't have enough reputation to upvote so thank you very much this helped a lot! – paochy Oct 11 '21 at 06:14
1

Problems with naming a variable after a builtin type in Python:

# this will pass
myDict = dict()

dict = {
 'one': 1,
 'two': 2
}

# this will *not* pass!
myDict = dict()

# nor this either :(
assert isinstance(myDict, dict)

But to proceed on despite the risks, here's the most straightforward approach for that:

x = globals()['dict']
print(x)
print(x['one'])
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • 1
    In my actual code I don't use 'dict' as the variable name I just used it for the example and forgot that it was a key word. Thank you very much this helps a lot! – paochy Oct 11 '21 at 04:55
  • No problem! glad that you found it helpful. – rv.kvetch Oct 12 '21 at 12:39