[Tutor] How to populate a dictionary

Alan Gauld alan.gauld at btinternet.com
Thu Jul 17 16:53:26 CEST 2008


<josetjr at msn.com> wrote

> The assignment is to create a dictionary from a text file:

ok, since it's 'homework' I won't give the whole answer but will try
to point you in the right direction.

> Your program should start by creating an empty dictionary called 
> dates.

> Then your program will get an array of ALL the keys for that 
> dictionary
> and then write a loop that will display all the key/value pairs.

OK, I'm not sure why they want you to build an array, its not really
necessary...

> you should have lines in it that say something like 
> "12/28/1948=Starting Day"

> open that file, read it, split it into lines, then for each line,

Again you don;t need to do all of that, Python has a function
readlines() that does it all for you.

> you will split that line by the equals = sign.
> The left side value is the Key and the Right Hand Side is the value.

> You will read this whole files, splitting each key/value pair and
> store them in a dictionary.

You can do this one line at a time rather than reading the file
then going back over it to split/store the data.

> Then write the loop which will get all the keys,
> SORT those keys and print out the key/value pairs.

OK, Again thats a bit off track as a sequence. I'd get the keys,
sort them then write a loop over the sorted keys to display the 
results.

myDictionary = { }

#AG-You were asked to call it dates!

inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :

Could just be:

for line in open("dates.txt"):

        if (inputLines [i] != "") :
            leftHandSide = inputLines [i].split ("=")
     rightHandSide = inputLines [i].split ("=")

These two lines do the same split. You need to store the first split
value in one variable and the second in the other. (Remember split()
returns a list). Try:

lhs, rhs = line.split('=')

     myDictionary [leftHandSide] = rightHandSide

theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
    print theKeys[i], myDictionary[ theKeys[i] ]

Rather than indexing via range(len()), a Python for loop is best used
to get the items directly. Thus:

for key in theKeys:
    print key, dates[key]

See how much more readable it is? And how much less typing!


If you have a recent version of Python you can also avoid the
business of extracting the keys and sorting them by using the
sorted() function on the dates directly as part of the for loop.
I'll leave that as an extra research topic! :-)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list