[Tutor] How to populate a dictionary

josetjr at msn.com josetjr at msn.com
Thu Jul 17 14:07:33 CEST 2008


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

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

"12/07/0526 = St Felix IV begins his reign as Catholic Pope"
"12/07/1109 = Crusaders capture Syria's harbor city of Tripoli"
"12/07/1191 = Richard Coeur de Lion and Crusaders defeat Saracens in Palestine"
"12/07/1290 = Jews are expelled from England by order of King Edward I"
"12/07/1442 = King Alfonso V of Arag¢n becomes king of Naples"

"Create a dictionary of dates. Each date you have in there should have a special event. An example would be that the dictionary would contain the following
NOTE: You must have at least 100 different dates. You can get this from lists on the internet if you like, but it must be something real, not just garbage or something just made up.
12/28/1929: My Birthday
1/1/1948: New Years Day 48
9/11: the big one


--------------------------------------------------------------------------------

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.
BUT: The dictionary setup file should exist OUTSIDE of the program, you should have lines in it that say something like "12/28/1948=Starting Day" or something like that. Your strategy will be to open that file, read it, split it into lines, then for each line, 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. Then write the loop which will get all the keys, SORT those keys and print out the key/value pairs. 

here is a sample of my code:

#!python
myDictionary = { }
inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :
        if (inputLines [i] != "") :
            leftHandSide = inputLines [i].split ("=")
     rightHandSide = inputLines [i].split ("=")
     myDictionary [leftHandSide] = rightHandSide
theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
    print theKeys[i], myDictionary[ theKeys[i] ]

Can anyone help?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080717/fafded06/attachment.htm>


More information about the Tutor mailing list