[Edu-sig] Rich Data Structures (cont.)

Kirby Urner urnerk at qwest.net
Wed Nov 2 20:50:55 CET 2005


Per previous post in this thread:

cities = {
  'Albany, N.Y.': [(42, 40, 'W'), (73, 45, 'N')],
  'Albuquerque, N.M.': [(35, 5, 'W'), (106, 39, 'N')],
  'Amarillo, Tex.': [(35, 11, 'W'), (101, 50, 'N')],
  'Anchorage, Alaska': [(61, 13, 'W'), (149, 54, 'N')],
  'Atlanta, Ga.': [(33, 45, 'W'), (84, 23, 'N')],
... }

You might want to introduce students to another formatting style in which
such data might be serialized:  XML.  

Using the above dict as grist for the mill ...

def makexml(thefile):
    f = open(thefile, 'w')
    f.write('<?xml version="1.0" encoding="ISO-8859-1"?>\n')
    for city in cities:  # cities is a global in this context
        loc = tuple([s.strip() for s in city.split(',')])
        if len(loc)==3:
            f.write('<city name="%s" state="%s" country="%s">\n' % loc)
        else:
            f.write('<city name="%s" state="%s">\n' % loc)
        f.write('\t<lat  deg="%s" min="%s" dir="%s" />\n' % cities[city][0])
        f.write('\t<long deg="%s" min="%s" dir="%s" />\n' % cities[city][1])
        f.write('</city>\n')
    f.close()

Usage:

>>> mymodule.makexml('cities.xml')
    
Output:

<?xml version="1.0" encoding="ISO-8859-1"?>
<city name="Syracuse" state="N.Y.">
	<lat  deg="43" min="2" dir="W" />
	<long deg="76" min="8" dir="N" />
</city>
<city name="Boise" state="Idaho">
	<lat  deg="43" min="36" dir="W" />
	<long deg="116" min="13" dir="N" />
</city>
<city name="Anchorage" state="Alaska">
	<lat  deg="61" min="13" dir="W" />
	<long deg="149" min="54" dir="N" />
</city>
<city name="Denver" state="Colo.">
	<lat  deg="39" min="45" dir="W" />
	<long deg="105" min="0" dir="N" />
</city>
<city name="Cleveland" state="Ohio">
	<lat  deg="41" min="28" dir="W" />
	<long deg="81" min="37" dir="N" />
</city>

And so on.

Where to go next with the XML tools would be up to you.  Or segue to a
discussion of other serialization techniques e.g. using Python's Pickle.

A useful curriculum segment would be to take the above xml and run it
through a parser to create a bunch of city objects with lat and long
attributes, i.e. XML used to instantiate objects.  That'd be a good "cave
painting" (= simplification, many essential aspects conveyed) of many real
world applications (e.g. XAML).

Kirby




More information about the Edu-sig mailing list