[Tutor] Re: Saving a dictionary to a text file [xml_pickle]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 24 Mar 2002 13:25:08 -0800 (PST)


> the pickle module (import pickle)
> allows you to pickle anything in a file just like you would pickle
> onions or eggs or beetroots. You can then unpickle it and be sure to get
> back what you put in and they taste just as fresh too.

I just noticed that David Mertz has written an 'xml_pickle' module that
does the same thing as the pickle module, except that what comes out is
almost readable.  *grin* Take a look:

    http://www-106.ibm.com/developerworks/library/xml-matters1/index.html
    http://www-106.ibm.com/developerworks/library/xml-matters2/index.html
    http://www-106.ibm.com/developerworks/xml/library/x-matters11.html


So we can  do something like this:


###
>>> import gnosis.xml.pickle as xml_pickle
>>> mydict = {'topic': 'saving dictionaries as text',
...           'technique': 'use xml_pickle',
...           'url':  'http://www-106.ibm.com/developerworks/'
                    + 'library/xml-matters1/index.html'}
>>> c = Container()
>>> c.dict = mydict
>>> xml_string = xml_pickle.XML_Pickler(c).dumps()
>>> print xml_string
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Container" id="135638484">
<attr name="dict" type="dict" id="136067228" >
  <entry>
    <key type="string" value="topic" />
    <val type="string" value="saving dictionaries as text" />
  </entry>
  <entry>
    <key type="string" value="url" />
    <val type="string"
value="http://www-106.ibm.com/developerworks/library/xml-matters1/index.html"
/>
  </entry>
  <entry>
    <key type="string" value="technique" />
    <val type="string" value="use xml_pickle" />
  </entry>
</attr>
</PyObject>
###


This xml_pickle apparently only likes to see class instances; in my
experiments, it complained when it saw a raw dictionary.  But we can
write something to automate this packing:


###
>>> class Container:
...     def __init__(self, dict): self.dict = dict
...
>>> def dict_to_xml(dict):
...     return xml_pickle.XML_Pickler(Container(dict)).dumps()
...
>>> dict_to_xml({1:'one', 2:'two'})
'<?xml version="1.0"?>\n<!DOCTYPE PyObject SYSTEM
"PyObjects.dtd">\n<PyObject module="__main__" class="Container"
id="136067692">\n<attr name="dict" type="dict" id="135569884" >\n
<entry>\n    <key type="numeric" value="1" />\n    <val type="string"
value="one" />\n  </entry>\n  <entry>\n    <key type="numeric" value="2"
/>\n    <val type="string" value="two" />\n
</entry>\n</attr>\n</PyObject>\n'

>>> def xml_to_dict(xml):
...     return xml_pickle.XML_Pickler().loads(xml).dict
>>> xml_to_dict(dict_to_xml({1: 'one'}))
{1: 'one'}
###


Hope this helps!