DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 }, u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]} def convert(data): if isinstance(data, basestring): return str(data) elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, data)) else: return data print DATA print convert(DATA)
Assumptions:
- You have imported the collections module and can use the abstract base classes that it provides.
- You can convert using the default encoding (use
data.encode('utf-8') , not str(data) if you need an explicit encoding).
If you need to support other types of containers, we hope that it will be obvious how to follow the pattern and add cases to them.
RichieHindle Aug 10 '09 at 12:03 2009-08-10 12:03
source share