My Big Dict.
John Hunter
jdhunter at ace.bsd.uchicago.edu
Wed Jul 2 08:12:52 EDT 2003
More information about the Python-list mailing list
Wed Jul 2 08:12:52 EDT 2003
- Previous message (by thread): My Big Dict.
- Next message (by thread): My Big Dict.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
>>>>> "Russell" == Russell Reagan <rreagan at attbi.com> writes: drs> f = open('somefile.txt') drs> d = {} drs> l = f.readlines() drs> for i in l: drs> a,b = i.split('!') drs> d[a] = b.strip() I would make one minor modification of this. If the file were *really long*, you could run into troubles trying to hold it in memory. I find the following a little cleaner (with python 2.2), and doesn't require putting the whole file in memory. A file instance is an iterator (http://www.python.org/doc/2.2.1/whatsnew/node4.html) which will call readline as needed: d = {} for line in file('sometext.dat'): key,val = line.split('!') d[key] = val.strip() Or if you are not worried about putting it in memory, you can use list comprehensions for speed d = dict([ line.split('!') for line in file('somefile.text')]) Russell> I have just started learning Python, and I have never Russell> used dictionaries in Python, and despite the fact that Russell> you used mostly non-descriptive variable names, I can Russell> still read your code perfectly and know exactly what it Russell> does. I think I could use dictionaries now, just from Russell> looking at your code snippet. Python rules :-) Truly. JDH
- Previous message (by thread): My Big Dict.
- Next message (by thread): My Big Dict.
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list