Python Forum
variable as dictionary name?
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
variable as dictionary name?
#1
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


Error:
NameError: name 'X0' is not defined
Reply
#2
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.
Reply
#3
So what would you recommend as is the simplest way to achieve this?
Reply
#4
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.
Reply
#5
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reference new dictionary keys with a variable slouw 4 2,836 May-07-2019, 03:30 AM
Last Post: slouw
  Dictionary named after variable value Alfred 1 3,031 Sep-02-2017, 01:24 PM
Last Post: sparkz_alot
  Build a multi-variable dictionary birdieman 4 4,969 Jan-06-2017, 04:34 PM
Last Post: birdieman
  calling an object variable in a dictionary sunhear 3 4,233 Dec-30-2016, 05:28 PM
Last Post: sunhear

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020