Question

Possible Duplicate:
how to extract a text file into a dictionary

I have a text file where I would like to change it into a dictionary in python. The text file is as follows. Where I would like to have the keys as "sun" and "earth" and "moon" and then for the values the orbital radius, period and such so that I can implement an animation solar system into quickdraw.

RootObject: Sun

Object: Sun
Satellites: Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris
Radius: 20890260
Orbital Radius: 0

Object: Earth
Orbital Radius: 77098290
Period: 365.256363004
Radius: 6371000.0
Satellites: Moon

Object: Moon
Orbital Radius: 18128500
Radius: 1737000.10
Period: 27.321582

My code so far is

def file():
    file = open('smallsolar.txt', 'r')
    answer = {}
    text = file.readlines() 
    print(text)



text = file() 
print (text)

I'm not sure what do now. Any ideas?

No correct solution

OTHER TIPS

answer = {} # initialize an empty dict
with open('path/to/file') as infile: # open the file for reading. Opening returns a "file" object, which we will call "infile"

    # iterate over the lines of the file ("for each line in the file")
    for line in infile:

        # "line" is a python string. Look up the documentation for str.strip(). 
        # It trims away the leading and trailing whitespaces
        line = line.strip()

        # if the line starts with "Object"
        if line.startswith('Object'):

            # we want the thing after the ":" 
            # so that we can use it as a key in "answer" later on
            obj = line.partition(":")[-1].strip()

        # if the line does not start with "Object" 
        # but the line starts with "Orbital Radius"
        elif line.startswith('Orbital Radius'):

            # get the thing after the ":". 
            # This is the orbital radius of the planetary body. 
            # We want to store that as an integer. So let's call int() on it
            rad = int(line.partition(":")[-1].strip())

            # now, add the orbital radius as the value of the planetary body in "answer"
            answer[obj] = rad

Hope this helps

Sometimes, if you have a number in decimal notation ("floating point numbers" in python-speak) in your file (3.14, etc), calling int on it will fail. In this case, use float() instead of int()

Read the file in one string instead of readlines() and then split on "\n\n", this way you will have a list of items, each describing your object.

Then you might want to create a class which does something like this:

class SpaceObject:
  def __init__(self,string):
    #code here to parse the string

    self.name = name
    self.radius = radius
    #and so on...

then you can create a list of such objects with

#items is the list containing the list of strings describing the various items
l = map(lambda x: SpaceObject(x),items).

And then simply do the following

d= {}
for i in l:
  d[i.name] = i
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top