+ 2
Is it possible to call separate dictionaries using a user input variable in Python 3? Any help much appreciated.
Apologies in advance if this is a school boy error. I am developing a Python 3 script to do a series of calculations using values in a dictionary. This works fine for a single dictionary but ideally I would like to be able to call separate variants of this dictionary using a user input variable. I have tried to call the separate dictionaries using the variable as the dictionary name e.g.: print(variable[X]) This however results in an error. is it possible to use dictionaries in this way?
6 Respuestas
+ 5
Yes, you can do such a thing, although that's probably not how you should approach this problem. Better to make a list of dictionaries and just call them by index. It's a lot easier to keep track, especially if there are many of them.
But anyway...
https://code.sololearn.com/cULv3uY3OlZ0/?ref=app
Just input 'a' or 'b'
+ 5
roughly said you need a kind of dictionary factory and your approach seems to be good.
dict1 = {.....}
dict2 ={.........}
dict3 = {...}
if input == 1:
variant = dict1
elif input ==2:
variant = dict2
variant is a dictionary
+ 5
inp = int(input("input:"))
dicts = [{....,},{...},{....,}]
thedict = dicts[inp]
+ 5
... or do what kuba says....always good idea (-;
+ 1
other answer is good. i just want to give you advice, python is flexible language, so try solve it by your self first. if you really cant solve it, than ask here :v
0
Thanks both. I shall have a go.