[Baypiggies] python newbie

Anna Ravenscroft annaraven at gmail.com
Mon Mar 6 18:05:07 CET 2006

On 3/6/06, Jerome Jabson <jjabson at yahoo.com> wrote:
> 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 = {}

don't ever use builtin names for variable names. It'll bite you.
mydict = {}

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! :-(

Describe "all wrong"? From your code above, I suspect you get the first
letter of the name as the key, rather than the whole name. You need to split
the line into separate words then rejoin them with ' '.join() for the value.

> someone give me some pointers on how to do this.

f = open("namer.txt", "r")

mydict = {}

for line in f:
   l = line.split()
   mydict[l[0]] = ' '.join(l[1:])

print mydict

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/baypiggies/attachments/20060306/f1196c33/attachment.html 

More information about the Baypiggies mailing list