How to pretty-print cyclic dictionaries?

Chris Rebert clp2 at rebertia.com
Thu Apr 29 12:56:23 EDT 2010


On Thu, Apr 29, 2010 at 9:23 AM, Dietrich Bollmann <diresu at web.de> wrote:
> Hi,
>
> I would like to represent graphs as cyclic dictionaries in Python.
>
> The python code for the graphs is generated by some other program
> (written in lisp) and I wonder what would be the best syntax for writing
> the cycles in Python?
>
> The following works:
>
>>>> a = {}
>>>> a['a'] = a
>
> As can be seen here:
>
>>>> a
> {'a': {...}}
>>>> a['a']
> {'a': {...}}
>>>> a['a']['a']
> {'a': {...}}
>>>> a['a']['a']['a']
> {'a': {...}}
>>>>
>
> but I wonder if there is some easier syntax to represent the cycles?
>
> "Tags" like the following would be ideal:
>
> [0] {'a': [0]}
>
> but is there something like this in Python?

Pretty sure that's a No.

> PS:  If there is such a representation, how could I make Python print it
> out?
>
> The normal printing is not very informative:
>
>>>> a
> {'a': {...}}
>
> And Pythons pretty-print functionality is not better either:
>
>>>> pprint.pprint(a)
> {'a': <Recursion on dict with id=3076782660>}
>
> Any idea?

If you want a prettier print, you could try serializing it to YAML and
printing the result out; YAML has syntax for "tags".

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list