variable as dictionary name? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: variable as dictionary name? (/thread-26290.html) |
variable as dictionary name? - diazepam - Apr-27-2020 Hi I am attempting to create 10 dictionaries without having to code them explicitly. The names of the dictionaries will be: X0, X1, X2, X3 .... X9 for x in range(11): a = str(x) dictionary_name = ('X'+a) dictionary_name = {}if i add type(dictionary_name) to the code it returns 'dict' However if i try to print one of the dictionaries print (dictionary_name) i get
RE: variable as dictionary name? - ndc85430 - Apr-27-2020 No, you don't dynamically create variables like that. If you want a collection of things, use a collection - you can have a list of dictionaries of course. Of course your code does that. On line 4, you set the value of dictionary_name to an empty dict, overwriting what was in there before. Line 3 doesn't even create a variable with the name X0 for example - it just sets the value of the variable to be that string. Both lines 3 and 4 are doing the same kind of thing - assigning a value to a variable. How could the same syntax be used for that and creating variable names dynamically? It couldn't, because the interpreter wouldn't be able to guess which one you meant.
RE: variable as dictionary name? - diazepam - Apr-27-2020 So what would you recommend as is the simplest way to achieve this? RE: variable as dictionary name? - ndc85430 - Apr-27-2020 Create a list of dictionaries. The other reason for using a collection rather than individual variables is that the latter is harder to work with. For a start, you have to change the program if you need more of them tomorrow than you did today. RE: variable as dictionary name? - deanhystad - Apr-27-2020 Or a dictionary of dictionaries. dictionaries = {} for d in range(10): dictionaries['X'+str(d)] = {}This is really strange looking code, but it does create ten dictionaries with the variables named 'X0' through 'X9'. If the dictionaries are part of a class, you could add the new dictionaries to the instance dictionary. class LotsaDictionaries: def __init__(self, count): for d in count: setattr(self, 'X'+str(d), {}) tenDictionaries = LotsaDictionaries(10) tenDictionaries.X0['whatever'] = 5 |