[Solved] For loop appending/updating a list/dict question

I am not sure what to forum to post it in, so I will post this here. I haven’t put this code in panda but I will soon after I figure out this list problem.

I am fairly new to python and so if you can give me any advice on my coding would be great!

So I am currently working on a solar system generator and have a problem with lists/dicts. This is the current code I am working on.

import random

r = {"t": [] }
r["t"] = ['Planet 1', 'Planet 2', 'Planet 3']

y = {'Planet Type': '', 'Planet Name': '', 'Location List': []}

for x in range(3):
	planet = random.randint(1,2)
	if planet == 1:
		y["Planet Type"] = "Terrestrial"
		r["t"][x] = y
	else:
		y["Planet Type"] = "Gas Giant"
		r["t"][x] = y

I wanted to roll randomly to see if the planet is a terrestrial planet or a gas giant and then append the type of planet in Y and then update the y to the R dictionary.

When I run my current code it runs the “for - loop” on it runs the r[“t”][x] 3 times and updates all the planets to be what ever it rolled. It then runs the random again and updates all three planets to be the same planet on what ever it rolled again.

I want to update the planet type once for first planet in loop 1 then start loop 2 and update the planet type for that planet then start loop 3 and do the same thing

Can anyone teach me a way to do this?

Also my second question is, In my current program I am using a lot of dictionaries and list to keep every thing neat so it currently looks like this:

planetInfo = {"Planet Name": '',"Planet Type": '', "Planet Char":'', "inSystem Loc": '', "inPlanet Loc List": [],}
systemInfo = {"Star Type": '',"PlanetNum": '',"Planet List":[planetInfo ]}
galaxyList = [systemInfo]

picture of how the code is suppose to look. To view it copy and paste it directly into ur IDE. looks like crap while its on the webpage

galaxyList = [ Star system 1] = {"Star Type": '',"PlanetNum": '',"Planet List":[ planet List]}
             [ Star system 2] = {"Star Type": '',"PlanetNum": '',"Planet List":[ planet List]}
             [ Star system 3] = {"Star Type": '',"PlanetNum": '',"Planet List":[ planet List]}
             [ Star system 4] = {"Star Type": '',"PlanetNum": '',"Planet List":[ Planet 1 ] = {"Planet Name": '',"Planet Type": '', "Planet Char":'', "inSystem Loc": '', "inPlanet Loc List": [ loaction on the planet List],}}
                                                                               [ Planet 2 ] = {"Planet Name": '',"Planet Type": '', "Planet Char":'', "inSystem Loc": '', "inPlanet Loc List": [ loaction on the planet List],}
                                                                               [ Planet 3 ] = {"Planet Name": '',"Planet Type": '', "Planet Char":'', "inSystem Loc": '', "inPlanet Loc List": [ loaction on the planet List],}
                                                                               [ Planet 4 ] = {"Planet Name": '',"Planet Type": '', "Planet Char":'', "inSystem Loc": '', "inPlanet Loc List": [ loaction on the planet List],}


How it is suppose to work, the GalaxyList holds a list containing all the systems (or systemInfo).

The sytemInfo is a dictionary that saves specific characteristic of that system as a keys.

The systemInfo has a Planet List that holds all the planets for that system in it. Each planet is also its own dictionary that holds the planets specific characteristics as keys.

I know I can save all that information in lists, but it guess messy fast, and if you don’t remember what position a value is in the list, your screwed. That is why I wanted to use dictionaries to make sorting the many different data types easier.

Is the way I am storing my data a good way? Or is there a better/faster way to do it?
Is there a different in performance between lists and dicts?
[/code]

Hi, about the first question, it seems you are still changing the same “planet” (the variable you named y), since y is the same reference for each step of the loop. If I’ve understood what you said, you should create a new reference y for each step of the loop i.e. inside the for-loop, not outside it.

About the second issue, you’d better use classes: the “logic bricks” of your project (like planets or star systems) are conceptually classes. You should use dictionaries or lists only when you have to model entities which are dictionaries or lists, actually. If you use classes then you can avoid using dictionaries (as instance, for the planets) so you can access fields immediately, and you can replace lists (as instance, for the galaxies) with a dictionary which has objects references as keys.

Thanks for your suggestion on the loop. It solved my problem, and I was able to complete my prototype with dict and lists.

I am currently remaking the program with proper classes.

I have a question though, in the following code I call the planetGen function 3 times for each planet in the system. How do I make sure each time the function is called that it creates and saves the planet variables as different planets each time it is called?

btw this is example code by no means my real program

from planet import PlanetGen

class SystemGen:
        def __init__(self):
                self.planetGen = PlanetGen()
                self.planetList = ["Planet 1", "Planet 2", "Planet 3"]
        def genPlanets(self):
                for x in range(len(self.planetList)):
                        self.planetGen()

When you create a new instance of an object, using a constructor, Python allocates new memory for it, and returns a reference to it. Python behaves like you said: it creates different planets; the problem was you were saving different references in the same place, so you were storing only the last reference, which overwrote the previous ones. It is up to you to store those references somewhere. For example the following code:

class MyClass(): pass
a = MyClass()
b = MyClass()
print a
print b

prints:

<__main__.MyClass instance at 0xb77d352c>
<__main__.MyClass instance at 0xb77d366c>

As you can see there are two different MyClass instances in memory, and a and b store them.

I had a hunch that’s what I needed to do, so something like this?

from planet import PlanetGen

class SystemGen:
        def __init__(self):
                self.planetGen = PlanetGen()
                self.planetList = ["Planet 1", "Planet 2", "Planet 3"]
        def genPlanets(self):
                for x in range(len(self.planetList)):
                        planetList[x] = planetGen()

Where each instance of x in the list would run the script?

After running these planet functions how would I be able to access each planet? Or after they are generated I wouldn’t be able to access them directly?

Also since this is is randomly generating a solar system, how would I go about saving this data? Would I save it a text file or would MySQL be better?

My knowledge about randomly generating data and the storing that data and then passing that data around is rather vague.

I will create a new post with the complete code I am currently working on, because this current thread has already been solved.

I would prefer this:

from planet import PlanetGen

class SystemGen:
  def __init__( self, planetsNumber ):
    self.planetList = []
    self.planetsNumber = planetsNumber
  def genPlanets( self ):
    for _ in range( self.planetsNumber ):
      self.planetList += [ PlanetGen() ]

Since self.planetGen is pointless, and the initialization of self.planetList is almost pointless (you do this only to retrieve the number of planets, which you could pass as an argument).

With objref.planetList[ index ], where 0 <= index < objref.planetsNumber.

It depends on the specific needs of your applications. There are several pros and cons for the various solutions.