Bryson Noble
Bryson Noble

Reputation: 351

How do I remove the quotation marks off of a string to be used as a variable - python

I am trying to pick a random item from my list and then pick a random item of the dictionary that has the same name as the item in the list.

import random

letters = ["a" , "b" , "c"]

a = {
  "item1": "Q",
  "item2": "W",
}
b = {
  "item1": "E",
  "item2": "R",
}
c = {
  "item1": "T",
  "item2": "Y",
}

item_num = random.randint(0, len(letters)-1)
print(letters[item_num].get([random.randint(0, 1)]))

I always get the same error: AttributeError: 'str' object has no attribute 'get', so I'm thinking that this is being caused because item_num would = something like 'a' instead of just a without the quotation marks. Any help is appreciated!

Upvotes: 0

Views: 110

Answers (2)

gmds
gmds

Reputation: 19895

The reason you get that error is that you're calling get on a str.

item_num is an int. You access an element of letters with it, which is fine because letters is a list. However, an element of letters is a str ('a', 'b' or 'c'), which you obviously can't call get on.

What you want to do is call get on the dictionary corresponding to the value of letters[item_num] you got. Accordingly, this probably does what you want:

import random

letters = ["a" , "b" , "c"]

a = {
  "item1": "Q",
  "item2": "W",
}
b = {
  "item1": "E",
  "item2": "R",
}
c = {
  "item1": "T",
  "item2": "Y",
}

source = random.choice(letters)

print(globals()[source].get(f'item{random.randint(1, 2)}'))

That said, it's likely not what you should do (programmatic access of global variables). Instead, you can consider:

  • Using a nested dictionary, where ['a', 'b', 'c'] are the keys
  • Not requiring additional processing of the random integer to get to the second-level keys (1, 2 as keys instead of 'item1', 'item2')

Example:

data = {'a': {1: 'Q',
              2: 'W'}
        ...}

Upvotes: 4

Juan Diego Garcia
Juan Diego Garcia

Reputation: 823

If you are using a global scope you can use globals() or eval the letter::

also for picking a random item from a dict, you need to know the keys and then pick a random one:

item_num = random.randint(0, len(letters)-1)
rand_key = random.choice(["item1", "item2"]) 
print(globals()[letters[item_num]].get(rand_key))
item_num = random.randint(0, len(letters)-1)
rand_key = random.choice(["item1", "item2"]) 
print(eval(letters[item_num]).get(rand_key))

Upvotes: 0

Related Questions