Reading a text file into a dictionary

Markus Wankus markus_wankus at hotmail.com
Tue Jan 7 14:41:44 EST 2003


You should be using:

"for key, value in mydict.iteritems():"

to get an iterator over key/value pairs.

Markus.


Andy Elvey 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
> 
> 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 -
> 
> ### Start of code ###
> import  UserDict
> class SeqDict(UserDict.DictMixin):
>     """Dictionary lookalike implemented with lists."""
>     def __init__(self):
>         self.keylist = []
>         self.valuelist = []
>     def __getitem__(self, key):
>         try:
>             i = self.keylist.index(key)
>         except ValueError:
>             raise KeyError
>         return self.valuelist[i]
>     def __setitem__(self, key, value):
>         try:
>             i = self.keylist.index(key)
>             self.valuelist[i] = value
>         except ValueError:
>             self.keylist.append(key)
>             self.valuelist.append(value)
>     def __delitem__(self, key):
>         try:
>             i = self.keylist.index(key)
>         except ValueError:
>             raise KeyError
>         self.keylist.pop(i)
>         self.valuelist.pop(i)
>     def keys(self):
>         return list(self.keylist)
> 
> # Now, read a comma-delimited file into the dictionary
> def readfile():
>     mydict = SeqDict()
> # NOTE - enter the path and filename WITHOUT quotes around it.
>     filename = raw_input('Enter name of file to open: ')
>     file = open(filename, 'r')
>     linenum=0
>     for line in file.readlines():
>             linenum+=1
>             mywords = string.split(line, sep=',')
> 
>             for word in mywords:
>                 if linenum == 1:
> # First row of data: the dictionary keys
>                     mydict.keylist.append(word)
>                     mydict.valuelist.append([])
>                 else:
> # The rest of the data
>                     mydict.valuelist.append(word)
>     for key, value in mydict:
>         print key, value
> 
> if __name__ == '__main__':
>     readfile()
> ### End of code ###
> 
> 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...  :-)
> 
> 
> 
> 





More information about the Python-list mailing list