J. Scull J. Scull - 28 days ago 8
Python Question

Creating multiple lists within a dictionary using an iteration



I am currently writing a small bit of logic for my HTML page. My aim is to create variables (lists) within an iteration (using the iteration to create the names of said lists as the amount of them will be unknown to the program). I am currently creating the lists like this:


maps={}
currentMap = elements[0].process
counter=0
for i in elements:
if(counter==0):
maps["mapsEle{0}".format(counter)]=[]
counter+=1
if(i.process!=currentMap):
currentMap = i.process
maps["mapEle{0}".format(counter)]=[]
counter+=1
else:
print("No change found, keeping heading the same.")


However as you can probably tell, this does not create a list but a string. I try to print the variables (e.g. mapsEle0) and it returns the variable name (e.g. print(mapsEle0) returns "mapsEle0") this too me is suprising as I would have thought if the dictionary is saving it as a string it would print "[]".


So I am looking for a way to create lists within the dictionary in that iteration I am using there, basically want to just reformat my declaration. Cheers in advance everyone :)


Edit:

As requested here is the code where I attempt to append. Please note I want to append 'i' into the lists and no the dictionary.

for i in maps:
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
#i.append(x)

Answer

The syntax of your print statement is wrong, if you want to access the contents of the dictionary, you need to use different notation.

Instead of print('mapsEle0') you need to do print(maps['mapsEle0']).

Update:

Unfortunately your description of what you want and your code are a bit conflicting, so if you can, please try to explain some more what this code is supposed to do.

for i in maps.iterkeys():
        for x in elements:
            if(x.process!=currentMap):
                currentMap=x.process
            elif(x.process==currentMap):
                maps[i].append(x)

This will iterate over all keys of maps ('mapsEle0'...'mapsEleN') and add x to the contained list if the elif condition is fulfilled.