1.1 --- a/vContent.py Wed Sep 24 14:58:48 2014 +0200
1.2 +++ b/vContent.py Wed Sep 24 16:05:03 2014 +0200
1.3 @@ -620,6 +620,43 @@
1.4 else:
1.5 return codecs.open(stream_or_string, "w", encoding=(encoding or default_encoding))
1.6
1.7 +def items_to_dict(items):
1.8 +
1.9 + """
1.10 + Return the given 'items' as a dictionary mapping names to tuples of the form
1.11 + (value, attributes).
1.12 + """
1.13 +
1.14 + d = {}
1.15 + for name, attr, value in items:
1.16 + if not d.has_key(name):
1.17 + d[name] = []
1.18 + if isinstance(value, list):
1.19 + d[name].append((items_to_dict(value), attr))
1.20 + else:
1.21 + d[name].append((value, attr))
1.22 + return d
1.23 +
1.24 +def dict_to_items(d):
1.25 +
1.26 + """
1.27 + Return 'd' converted to a list of items suitable for serialisation using
1.28 + iterwrite.
1.29 + """
1.30 +
1.31 + items = []
1.32 + for name, value in d.items():
1.33 + if isinstance(value, list):
1.34 + for v, a in value:
1.35 + if isinstance(v, dict):
1.36 + items.append((name, a, dict_to_items(v)))
1.37 + else:
1.38 + items.append((name, a, v))
1.39 + else:
1.40 + v, a = value
1.41 + items.append((name, a, dict_to_items(v)))
1.42 + return items
1.43 +
1.44 # Public functions.
1.45
1.46 def parse(stream_or_string, encoding=None, non_standard_newline=0, parser_cls=None):
1.47 @@ -708,4 +745,17 @@
1.48
1.49 return (writer_cls or StreamWriter)(_writer)
1.50
1.51 +def to_dict(node):
1.52 +
1.53 + "Return the 'node' converted to a dictionary representation."
1.54 +
1.55 + name, attr, items = node
1.56 + return {name : (isinstance(items, list) and items_to_dict(items) or items, attr)}
1.57 +
1.58 +def to_node(d):
1.59 +
1.60 + "Return 'd' converted to a items-based representation."
1.61 +
1.62 + return dict_to_items(d)[0]
1.63 +
1.64 # vim: tabstop=4 expandtab shiftwidth=4