Reading a text file into a dictionary

Bengt Richter bokr at oz.net
Tue Jan 7 21:48:27 CET 2003


On Wed, 8 Jan 2003 08:06:27 +1300, "Andy Elvey" <andy.elvey at paradise.net.nz> wrote:

>Hi all -
>
>( I'm running Python 2.3a1 under win98 )
> I have a comma-delimited file which I'm trying to read into a Python
> dictionary (actually, a dictionary implemented using lists). The dictionary
> code is exactly as shown in the "What's new" part of the Python 2.3a1
> release notes.
> The file is as follows -
>Country,City,var1,var2,var3
>Australia,Sydney,214,105,478
>Australia,Melbourne,345,26,200
>Australia,Perth,109,217,809
>
I recognize something like this from about a month ago ;-)

>The first row (the column headings) will be the keys, and the rest of the
>data is the values to be associated with the keys.
>My code is as follows -
[... snipped ...]
>
>When I run this, it crashes at the line "for key, value in mydict"
>with the message "ValueError - too many values to unpack".
> Hmmmm .....
>So, any help is much appreciated. Thanks in advance...  :-)

First, realize that you can solve this problem yourself, if you start
investigating. Otherwise it's like being a little lost in the woods and
asking for someone to lead you out by the hand. Any number of people
here could make your code work or write other code to do the job (as they
understand it from reading between the lines). But I think the help you
need is in how to help yourself.

When a big glob of code isn't doing what you hoped, take it a piece at a time,
and see what is working. If your code looks like a single piece already, look again ;-)

If you haven't got pieces that you can test separately, at least write something
that runs a test case automatically on some data, so you can cycle through tests fast.
Then if it dies, put in some temporary print statements to see what data looks like as
it's flowing through your program. E.g., do you know what your lines are as they are read?
Will you be surprised if you see a \n at the end, and at the end of your last "word"?
Will you be surprised if a whole line is nothing but a single \n?

What do the lists that you are depending on look like just before the exception is raised?

Are you sure you know what for "k,v in something:" tries to do with a custom "something"?
Have you read about iteration? Is your base class supplying iteration support? If so,
how would it know about your special lists? Or should your class have an __iter__ etc.?

Hope this gets you a little further ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list