[Baypiggies] python newbie

Tung Wai Yip tungwaiyip at yahoo.com
Mon Mar 6 18:15:18 CET 2006


I'd introduce the zen of Python programming, the "print" statement.

dict = {}
f = open("text-file", "r)
for line in f:
    items = line

    # add this an temp working aid
    print 'line - ', items[0], ',', items[1:]

    dict[items[0]] = items[1:]
print dict


It helps you visualize what "item" really looks like. It is not what you  
think.

In this case you should build a little state machine to handle the sequence

   NAME, VALUE, SEPARATOR, NAME, VALUE, SEPARATOR, ... and so on.

There you also have a chance to decide how flexiable you want to allow the  
separators, EOF condition, etc.

Wai Yip


> I'm having problems trying to parse a text file and
> separating it's contents into a dictionary. The file
> as something like:
>
> name
> This is the description of the name.
>
> another_name
> Another description of this name.
>
> The dictionary should look like:
>
> dict = {name: This is the description of the name.,
> another_name: Another discription of this name}
>
> I tried doing something like:
>
> dict = {}
> f = open("text-file", "r)
> for line in f:
>    items = line
>     dict[items[0]] = items[1:]
> print dict
>
> but the dictionary comes out all wrong! :-( Can
> someone give me some pointers on how to do this.
>
> Help is much appreciated!
> Jeff
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> http://mail.python.org/mailman/listinfo/baypiggies




More information about the Baypiggies mailing list