Packing a simple dictionary into a string - extending struct?

John Machin sjmachin at lexicon.net
Wed Jun 20 08:50:31 EDT 2007


On Jun 20, 9:19 pm, "Jonathan Fine" <J.F... at open.ac.uk> wrote:
> Hello
>
> I want to serialise a dictionary, whose keys and values are ordinary strings
> (i.e. a sequence of bytes).
>
> I can of course use pickle, but it has two big faults for me.
> 1.  It should not be used with untrusted data.
> 2.  I want non-Python programs to be able to read and write these
> dictionaries.
>
> I don't want to use XML because:
> 1.  It is verbose.
> 2.  It forces other applications to load an XML parser.
>
> I've written, in about 80 lines, Python code that will pack and unpack (to
> use the language of the struct module) such a dictionary.  And then I
> thought I might be reinventing the wheel.  But so far I've not found
> anything much like this out there.  (The closest is work related to 'binary
> XML' -http://en.wikipedia.org/wiki/Binary_XML.)
>
> So, what I'm looking for is something like and extension of struct that
> allows dictionaries to be stored.  Does anyone know of any related work?
>

C:\junk>copy con adict.csv
k1,v1
k2,v2
k3,v3
^Z
        1 file(s) copied.

C:\junk>\python25\python
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> adict = dict(csv.reader(open('adict.csv', 'rb')))
>>> adict
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
>>> csv.writer(open('bdict.csv', 'wb')).writerows(adict.iteritems())
>>> ^Z

C:\junk>type bdict.csv
k3,v3
k2,v2
k1,v1

C:\junk>

Easy enough?
HTH,
John




More information about the Python-list mailing list