[python-win32] Converting types for deep lists or Discitonnaries

Tim Roberts timr at probo.com
Thu May 21 18:46:39 CEST 2009


Dominick Lauzon wrote:
>
> I need to convert a multi-level and multi-type list and dictionary
> (keys and values) to string format.
>
>  
>
> Is there a way to do this globally rather than iterating item to
> str(item)?
>

One easy way is to use pprint.pformat.  Many folks use pprint to do
pretty printing of nested data structures, but the module also contains
a pformat function that returns a string:

C:\VS9\VC\bin>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [ 1, 2, [ '333', { 'a': 42, 'b': 43 }, 777 ], (99, 100) ]
>>> import pprint
>>> a = pprint.pformat(a)
>>> print a
[1, 2, ['333', {'a': 42, 'b': 43}, 777], (99, 100)]
>>>

The string can be converted back to a data structure using eval, with
appropriate caution.

There's also the option of using "pickle", which was designed to
serialize and deserialize Python data structures.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list