Is it possible to call separate dictionaries using a user input variable in Python 3? Any help much appreciated. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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?

4th Feb 2018, 8:22 PM
Prometheus1248
6 ответов
+ 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'
4th Feb 2018, 8:36 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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
4th Feb 2018, 8:38 PM
Oma Falk
Oma Falk - avatar
+ 5
inp = int(input("input:")) dicts = [{....,},{...},{....,}] thedict = dicts[inp]
4th Feb 2018, 8:42 PM
Oma Falk
Oma Falk - avatar
+ 5
... or do what kuba says....always good idea (-;
4th Feb 2018, 8:43 PM
Oma Falk
Oma Falk - avatar
+ 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
4th Feb 2018, 10:06 PM
Kevin AS
Kevin AS - avatar
0
Thanks both. I shall have a go.
4th Feb 2018, 8:58 PM
Prometheus1248