[Tutor] How to populate a dictionary

Michiel Overtoom motoom at xs4all.nl
Thu Jul 17 15:02:22 CEST 2008

josetjr wrote...

>Hello, I am taking python this summer, and have run into a problem.

Let me suggest some improvements. You can process all the lines in a
textfile like this:

    for line in open("dates.txt").readlines():
        print line
Furthermore, if you have a string in the form of "ABC=DEF", you can split it
like this:


To enumerate the keys of a dictionary in alphabetical order, you can use:

    for k in sorted(d):
        print k
So, your little homework program becomes more pythonic like this:

for line in open("dates.txt").readlines(): 
    line=line.strip("\n\"") # clean the line a bit; strip off the newline
and quotes

for k in sorted(history):
    print k,history[k]

Have a nice day,

"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil

More information about the Tutor mailing list