trying to get a dictionary from user input, there will be multiple dictionary's to reference from, user is expected to input "A1" when asked, and expected to "get something 1" as a result, but this gives "string indicies must be integers". any help is appreciated.
A = {
"A1": "something1",
"A2": "something2",
}
B = {
"B1": "somethingelse1",
"B2": "somethingelse2",
}
user_error = input("what is your error? ").upper()
first_half = user_error[0]
print(first_half[user_error])
CodePudding user response:
There is a lot of confusion going on in your post, so I cleaned it up a little and created a solution for you:
A = {
"A1": "something1",
"A2": "something2",
}
B = {
"B1": "somethingelse1",
"B2": "somethingelse2",
}
user_error = input("what is your error? ").upper()
dict_name = user_error[0]
selected_dict = locals()[dict_name]
print(selected_dict[user_error])
Unfortunately, I don't see a simpler way than to use locals
, which you are probably the least familiar with. But more importantly in order to undertand the rest of the solution in particular, I strongly recommend to read up on the basics of Python, e.g. here.
CodePudding user response:
Two input is necessary for this. Example code:
A = {
"A1" : "something1",
"A2" : "something2"
}
B = {
"B1" : "somethingelse1",
"B2" : "somethingelse2"
}
which_dict = input("what is your choice? ").upper()
selected = {}
if which_dict == "A": selected = A
else: selected = B
user_error = input("what is your error? ").upper()
first_half = selected[user_error]
print(first_half)