How to pretty-print cyclic dictionaries?

Dietrich Bollmann diresu at
Thu Apr 29 12:23:07 EDT 2010


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?

Thanks, Dietrich

PS:  If there is such a representation, how could I make Python print it

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?

Thanks again :)

More information about the Python-list mailing list